update 和case的联合用法

如果更新的时候需要对2个条件都要判断的可以用一个update +case来完成
例子如下:
declare @a table(id int,EndTime datetime,classid int)
insert @a
select 1,dateadd(day,-1,getdate()),1
union all
select 2,dateadd(day,1,getdate()),2
union all
select 3,dateadd(day,-1,getdate()),2
union all
select 4,dateadd(day,1,getdate()),1
select * from @a
select getdate()
update @a
set EndTime=dateadd(hh,case when Classid=1 then 24 else 72 end,case when EndTime>=getdate() then Endtime else getdate()end)
select * from @a

(4 行受影响)
id          EndTime                 classid
----------- ----------------------- -----------
1           2008-07-24 11:52:53.827 1
2           2008-07-26 11:52:53.827 2
3           2008-07-24 11:52:53.827 2
4           2008-07-26 11:52:53.827 1

(4 行受影响)


-----------------------
2008-07-25 11:52:53.827

(1 行受影响)

(4 行受影响)

id          EndTime                 classid
----------- ----------------------- -----------
1           2008-07-26 11:52:53.827 1
2           2008-07-29 11:52:53.827 2
3           2008-07-28 11:52:53.827 2
4           2008-07-27 11:52:53.827 1

(4 行受影响)

你可能感兴趣的:(update 和case的联合用法)