如何在脚本中交换sql server中的两条记录

时间:2013-09-09 06:46:58

标签: sql sql-server-2008

我想在sql server中交换两条记录,例如

enter image description here

我该怎么做?

3 个答案:

答案 0 :(得分:1)

您可以使用JOIN这样的一个声明执行此操作

UPDATE t1
   SET t1.id = t2.id
  FROM table1 t1 JOIN table1 t2
    ON (t1.id = 1 AND t2.id = 2)
    OR (t1.id = 2 AND t2.id = 1)

更新后的输出:

| ID | NAME | FAMILY |
|----|------|--------|
|  1 | Mary | Simson |
|  2 | Jame |  Ander |

这是 SQLFiddle 演示

答案 1 :(得分:0)

SELECT
    *,CASE WHEN id=123 then 987 ELSE 123 END AS JoinId
    INTO #Temp
    FROM YourTable
    WHERE ID in (123,987)

--swap values
UPDATE y
    SET col1=t.col1
        ,col2=t.col2
    FROM YourTable        y
        INNER JOIN #Temp  t ON y.id =t.JoinId
    WHERE ID in (123,987)

答案 2 :(得分:0)

在ID为identity的情况下,您可以使用@Vaibs_Cool和@ user814064之间的组合解决方案

类似这样的事情

DECLARE @aID INT, @bID INT
SELECT @aID = 123, @bID = 987

;WITH ToSwap AS
(
    SELECT CASE WHEN id = @aID THEN @bID ELSE @aID END AS id, [Name], [Family]
    FROM YourTable
    WHERE id IN (@aID, @bID)
)
UPDATE YourTable
SET [Name]=ToSwap.[Name], [Family] = ToSwap.[Family]
FROM YourTable 
INNER JOIN   ToSwap  ON YourTable.id =ToSwap.Id