Reputation: 752
I have a table with these values:
Name | id
----------------
Blue guy | 20
Green girl | 10
The id
column is a unique value. What I want is to update blue guy id to 10 and in that same query I want to update green girl id to 20. My current SQL
query is:
UPDATE colorpeople SET id = 20
WHERE name = 'Blue guy';
Where can I specify to update the green girl to?
Upvotes: 1
Views: 3709
Reputation: 3890
try this:
UPDATE colorpeople
SET id = (case
when name = 'Blue guy' then 10
when name = 'Green girl' then 20
else id = id
end)
Upvotes: 4
Reputation: 71
Please try below script :
ALTER TABLE colorpeople DROP CONSTRAINT PK_colorpeople
UPDATE colorpeople SET ID = 10 WHERE Name = 'Blue guy'
UPDATE colorpeople SET ID = 20 WHERE Name = 'Green girl'
ALTER TABLE colorpeople ADD CONSTRAINT PK_colorpeople PRIMARY KEY /* CLUSTERED */ (ID)
Upvotes: 1
Reputation: 1271231
The best way of doing this uses a WHERE
clause:
UPDATE colorpeople
SET id = (case when name = 'Blue guy' then 10
when name = 'Green girl' then 20
end)
WHERE name in ('Blue guy', 'Green girl');
Upvotes: 0
Reputation: 1
if you want to update a unique key that already exists
UPDATE colorpeople SET id = -20 WHERE naam = 'Blue guy';
UPDATE colorpeople SET id = -10 WHERE naam = 'Green girl';
UPDATE colorpeople SET id = -id WHERE naam in ('Blue guy', 'Green girl');
Upvotes: -1
Reputation: 130
You should try something like this :
INSERT INTO colorpeople id VALUES 10, 20
ON DUPLICATE KEY UPDATE id=VALUES(id);
Upvotes: 0