gpt4 book ai didi

sql-server - 如何使用一条 UPDATE 语句更新两列值,反之亦然

转载 作者:行者123 更新时间:2023-12-02 01:01:57 25 4
gpt4 key购买 nike

我刚从我的 friend 那里得到这个问题。我有一张如下所示的表格

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 '3 的 SURNAME 更新 ID '1' 的 NAME 列值' 反之亦然,我想用 IDNAME 更新 ID '3' 的 SURNAME 列值 ' 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语句来做到这一点?

最佳答案

您可以使用两个 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

关于sql-server - 如何使用一条 UPDATE 语句更新两列值,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27579514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com