SQL Server SQL copy and paste table data into that same table by only changing one value

xzabzqsa  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(102)

I want to copy and paste table data into that same table by only changing one value

Example: BillingLocationID

It's not possible to do it one by one inserting there are large number of rows.

I've created a #temptable and changed the value that I wanted to change

select *
into #temptablepop
from Productlocation
where BillingLocationID = 1
and DepartmentID = 3

update #temptablepop set BillingLocationID = '3'

insert into ProductLocation
select * from #temptablepop

and this gives me an error

An explicit value for the identity column in table 'ProductLocation' can only be specified when a column list is used and IDENTITY_INSERT is ON.

So I tried

SET IDENTITY_INSERT Productlocation ON

Then I'm getting this

An explicit value for the identity column in table 'ProductLocation' can only be specified when a column list is used and IDENTITY_INSERT is ON

Then I tried this method

INSERT Into tableA ([c1], [c2], [c3], [c4], [c5] ) 
SELECT [c1], [c2], [c3], [c4], [c5] FROM tableB

And still it gives me this

Violation of PRIMARY KEY constraint 'PK_dbo.ProductLocation'. Cannot insert duplicate key in object 'dbo.ProductLocation'. The duplicate key value is (4284).

Is there any other way?

jaxagkaj

jaxagkaj1#

You shouldn't specify the Id.

Just do this:

INSERT Into tableA ([c2], [c3], [c4], [c5], [BillingLocationID]) 
SELECT [c2], [c3], [c4], [c5], '3' [BillingLocationID] 
FROM Productlocation 
WHERE BillingLocationID = 1 AND DepartmentID = 3

Where C2, C3, etc the columns you want to copy.

相关问题