开发者

SQL Server : Changing an ID to an already existing one (merge) HOW TO?

I have two records that are the same in a table (entered by mistake). Both IDs are used as foreign key in other tables. I want to update the foreign keys to one "orignal" element and delete the other one. The problem is that it's possible that the UPDATE of the foreign key will generate a constraint exception (if the foreign key with the original element already exists).

So I would do something like :

UPDATE foreignTable SET id=1 WHERE id=2 
DELETE FROM fi开发者_如何学JAVArstTable WHERE id=2

The problem is with the UPDATE, I would like to do the UPDATE if the row doesn't already exists, if yes just DELETE the row. How do you do that?


UPDATE ft
    SET id = 1
    FROM foreignTable ft
        LEFT JOIN foreignTable ft2
            ON ft.PrimaryKey = ft2.PrimaryKey
                AND ft2.id = 1
    WHERE ft.id = 2
        AND ft2.PrimaryKey IS NULL

DELETE FROM foreignTable
    WHERE id = 2


If you are using SQL Server 2008, have a look at the MERGE statement.

It allows you to insert the missing rows, update the existing one and delete those who have to be deleted.

http://technet.microsoft.com/en-us/library/bb510625.aspx

If you use an older version, you will have to copy your data to a temporary table, delete the data from the existing one and reinsert from the temp table.

Be sure to use a transaction and make a backup of your table to avoid data loss.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜