我刚从朋友处得到这个问题。 我有一张表,如下所示
DECLARE @table TABLE
(
ID INT IDENTITY(1,1) NOT NULL,
NAME VARCHAR(30),
SURNAME VARCHAR(30)
)
INSERT INTO @table(NAME, SURNAME)
VALUES('Mohit', 'Vaghadiya'),
('Paresh', 'Panchal'),
('Devid','Pietersen'),
('kapil','Soni')
===================================
| ID | NAME | SURNAME |
=================================
| 1 | Mohit | Vaghadiya |
| 2 | Paresh | Panchal |
| 3 | Devid | Pietersen |
| 4 | kapil | Soni |
===================================
我只想更新 ID ' 1'的 NAME 列值使用 ID 的 SURNAME ' 3'反之亦然我想更新 ID ' 3'的 SURNAME 列值使用 NAME ID ' 1'
输出
===================================
| ID | NAME | SURNAME |
===================================
| 1 | Pietersen | Vaghadiya |
| 2 | Paresh | Panchal |
| 3 | Devid | Mohit |
| 4 | kapil | Soni |
===================================
我知道我们可以这样做
DECLARE @name VARCHAR(30)
SELECT @name = SURNAME FROM @table WHERE ID = 3
UPDATE @table
SET SURNAME = (SELECT NAME FROM @table WHERE ID = 1)
WHERE ID = 3
UPDATE @table
SET NAME = @name
WHERE ID = 1
但是,有没有办法通过只执行一个 UPDATE 语句来实现呢?
答案 0 :(得分:3)
您可以使用两个case表达式,一个用于名称,另一个用于姓氏:
UPDATE @table
SET name =
case
when ID = 1 then (SELECT SURNAME FROM @table WHERE ID = 3)
else name
end,
surname =
case
when ID = 3 then (SELECT NAME FROM @table WHERE ID = 1)
else surname
end
WHERE ID in (1, 3)
<强> sqlFiddle 强>
答案 1 :(得分:1)
您可以使用与第一组表中的第1行和另一表中的第3行匹配的条件来连接表。您可以使用x+y-x = y
和x+y-y = x
这一事实,即表达式(3+1) - ID
计算另一个ID,即t1.ID = 4 - t2.ID
。
然后您需要更新值的条件,以便您只更改每条记录中的正确值:
update t1
set
NAME = case t1.ID when 1 then t2.SURNAME else t1.NAME end,
SURNAME = case t1.ID when 3 then t2.NAME else t1.SURNAME end
from
MyTable t1
inner join MyTable t2 on t2.ID = 4 - t1.ID
where
t1.ID in (1,3)
答案 2 :(得分:0)
这应该适合你:
DECLARE @name VARCHAR(30)
SELECT @name = SURNAME FROM @table WHERE ID = 3
UPDATE @table
SET SURNAME = CASE
WHEN ID = 3
THEN (SELECT NAME FROM @table WHERE ID = 1)
ELSE SURNAME
END
,NAME = CASE
WHEN ID = 1
THEN @name
ELSE NAME
END
WHERE id IN (1,3)
只需使用CASE
语句来处理这两种情况,然后先更新SURNAME
列,然后更新NAME
列。
答案 3 :(得分:0)
UPDATE @table
SET SURNAME = CASE
WHEN ID = 3 THEN (SELECT NAME
FROM @table
WHERE ID = 1)
ELSE SURNAME
END,
NAME = CASE
WHEN ID = 1 THEN (SELECT SURNAME
FROM @table
WHERE ID = 3)
ELSE NAME
END
WHERE id IN ( 1, 3 )