更新 SQL 中的多条记录

发布于 2024-11-03 05:36:45 字数 130 浏览 1 评论 0原文

我如何使用 SQL 在一条语句中更新多条记录?

UPDATE records
   SET name='abc' where id=3,
   SET name='def' where id=1

How can i update multiple records in a single statement like this with SQL?:

UPDATE records
   SET name='abc' where id=3,
   SET name='def' where id=1

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

花伊自在美 2024-11-10 05:36:45

对于只有几条记录,您可以使用:

update records
set name = case id
  when 1 then 'def'
  when 3 then 'abc'
end
where id in (1, 3)

更灵活的是创建一个可以加入更新的结果:

update r
set name = x.name
from records r
inner join (
  select id = 1, name = 'abc' union all
  select 3, 'def' union all
  select 4, 'qwe' union all
  select 6, 'rty'
) x on x.id = r.id

For just a few records, you could use:

update records
set name = case id
  when 1 then 'def'
  when 3 then 'abc'
end
where id in (1, 3)

A bit more flexible is to create a result that you can join into the update:

update r
set name = x.name
from records r
inner join (
  select id = 1, name = 'abc' union all
  select 3, 'def' union all
  select 4, 'qwe' union all
  select 6, 'rty'
) x on x.id = r.id
多彩岁月 2024-11-10 05:36:45

您可以简单地将更新与案例陈述结合起来,例如

UPDATE records
   SET name =
     CASE
       WHEN id = 3 THEN 'abc'
       WHEN id = 1 THEN 'def'
       ELSE name
     END

You can simply combine an update with a case statement such

UPDATE records
   SET name =
     CASE
       WHEN id = 3 THEN 'abc'
       WHEN id = 1 THEN 'def'
       ELSE name
     END
兔姬 2024-11-10 05:36:45
;WITH vals(id, name)
     AS (SELECT 3,'abc'
         UNION ALL
         SELECT 1,'def')
UPDATE r
SET    name = vals.name
FROM   records r
       JOIN vals
         ON vals.id = r.id  
;WITH vals(id, name)
     AS (SELECT 3,'abc'
         UNION ALL
         SELECT 1,'def')
UPDATE r
SET    name = vals.name
FROM   records r
       JOIN vals
         ON vals.id = r.id  
嘦怹 2024-11-10 05:36:45

标准 SQL:2003 语法(适用于 SQL Server 2008 及以上版本):

MERGE INTO records 
   USING (
          VALUES (1, 'def'), 
                 (3, 'abc')
         ) AS T (id, name)
      ON records.id = T.id
WHEN MATCHED THEN
   UPDATE 
      SET name = T.name;

请注意,NAMERECORDS 是 SQL 保留字。

Standard SQL:2003 syntax (works on SQL Server 2008 onwards):

MERGE INTO records 
   USING (
          VALUES (1, 'def'), 
                 (3, 'abc')
         ) AS T (id, name)
      ON records.id = T.id
WHEN MATCHED THEN
   UPDATE 
      SET name = T.name;

Note that NAME and RECORDS are SQL reserved words.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文