例如,我想在 sql server 中交换两条记录
我该怎么做?
您可以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)
更新后的输出:
| 身份证 | 姓名 | 家庭 | |----|--------|--------| | 1 | 玛丽 | 西姆森 | | 2 | 詹姆斯 | 安德 |
这是SQLFiddle演示
如果 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
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)