在SQL中更新多个记录

时间:2011-04-25 12:05:21

标签: sql sql-server sql-update

如何使用SQL更新像这样的单个语句中的多个记录?:

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

4 个答案:

答案 0 :(得分:16)

您可以简单地将更新与案例陈述(例如

)结合起来
UPDATE records
   SET name =
     CASE
       WHEN id = 3 THEN 'abc'
       WHEN id = 1 THEN 'def'
       ELSE name
     END

答案 1 :(得分:16)

只需几条记录,您就可以使用:

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

答案 2 :(得分:5)

;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  

答案 3 :(得分:3)

标准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保留字。