Inserting rows from one table to another another with PK column value incrementing

  • Hi,

    We are using Sql server 2008 R2 express. We have two tables,table1(id int,name nvarchar(50)) and table2(id int,name nvarchar(50)). For both tables id is primary key.I want to move rows from table2 to table1 with PK value incrementing i.e i want max(id)+1 of table1 for all rows copying .I tried this query

    declare @root int

    select @root=max(id+1) from Bgd_common.dbo.table1

    insert into Bgd_common.dbo.table1(id,Name) select @root,name from Bgd_common.dbo.table2

    But its giving error as ''Violation of PRIMARY KEY constraint 'PK_Table1'. Cannot insert duplicate key in object 'dbo.Table1'.". How to do?

  • As your not incrementing @root your inserting the same value every time.

    You would want to row_number the table then add the max ID value to it so that it is incremented and every value is different.

    Something like

    declare @root int

    select @root=max(id) from Bgd_common.dbo.table1

    insert into Bgd_common.dbo.table1(id,Name) select @root + ROW_NUMBER() OVER(ORDER BY ID),name from Bgd_common.dbo.table2

  • anthony.green (3/26/2013)


    As your not incrementing @root your inserting the same value every time.

    You would want to row_number the table then add the max ID value to it so that it is incremented and every value is different.

    Something like

    declare @root int

    select @root=max(id) from Bgd_common.dbo.table1

    insert into Bgd_common.dbo.table1(id,Name) select @root + ROW_NUMBER() OVER(ORDER BY ID),name from Bgd_common.dbo.table2

    That worked very fine.Thank you

  • Will suggested query work for MS access database?

  • Probably not, Google to see if Access supports the ROW_NUMBER() ranking function.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply