SQL如何用一条语句批量修改表中不同数据
的有关信息介绍如下:
SQL如何用一条语句批量修改表中不同数据,可以使用where条件中过滤出不同的数据,也可以在修改值的地方判断数据给定不同的值,也可以两者兼有
打开SQL Server Management管理工具,使用sql语句创建一张测试表:
create table tblUpdate(
Id varchar(40) NOT NULL,
Col1 varchar(50) NULL,
Col2 varchar(50) NULL
);
在测试表中,插入3条测试数据:
insert into tblUpdate(Id, Col1, Col2) values('1', '张三', '男');
insert into tblUpdate(Id, Col1, Col2) values('2', '李四', '男');
insert into tblUpdate(Id, Col1, Col2) values('3', '王五', '女');
查询刚刚插入的数据:
select * from tblUpdate;
使用一条语句批量修改整个表的数据,慎用:
update tblUpdate set Col2 = '女';
使用一条语句批量修改指定条数的记录:
update tblUpdate set Col2 = '第二次修改' where Id = 1 or Id = 2;
使用一条语句批量修改这三条数据(按条件修改值):
update tblUpdate
set Col2 = (case when Id = 1 then '第三次修改1'
when Id = 2 then '第三次修改2'
else '第三次修改'
end
);
使用一条语句批量修改数据,使用where和case when:
update tblUpdate
set Col2 = (case when Id = 1 then '第三次修改5'
when Id = 2 then '第三次修改5'
else '第三次修改5'
end
)
where Id = 1 or Id = 2;



