sql 条件查询对应更新,高手帮下忙。
本帖最后由 gzw13999 于 2013-05-28 01:37:05 编辑
--数据
declare @tab1 table(id int,mun1 int,mun2 int)
insert @tab1
select 1,200,110 union all
select 2,150,11 union all
select 3,500,42 union all
select 4,180,99 union all
select 5,70,32;
select * from @tab1
declare @tab2 table(id int,[time] datetime)
insert @tab2
select 1,'2013-05-28 01:23:08.467' union all
select 2,'2013-05-28 01:23:08.467' union all
select 3,'2013-05-28 01:23:08.467' union all
select 4,'2013-05-28 01:23:08.467' union all
select 5,'2013-05-28 01:23:08.467' ;
select * from @tab2
以上tab1 tab2 两个表 如果tab1 mun2列值大于mun1列值的50% 就把tab2相对应ID的行[time]增加一天时间。
也就是上述tab1表测试数据的1行和4行为值大于50%条件 然后更新tab2 1行和4行[time]增加一天时间
[解决办法]
update @tab2 set time=DATEADD(day,1,time) where id in(
select id from @tab1 where mun2>mun1*0.5)
[解决办法]
declare @tab1 table(id int,mun1 int,mun2 int)
insert @tab1
select 1,200,110 union all
select 2,150,11 union all
select 3,500,42 union all
select 4,180,99 union all
select 5,70,32;
declare @tab2 table(id int,[time] datetime)
insert @tab2
select 1,'2013-05-28 01:23:08.467' union all
select 2,'2013-05-28 01:23:08.467' union all
select 3,'2013-05-28 01:23:08.467' union all
select 4,'2013-05-28 01:23:08.467' union all
select 5,'2013-05-28 01:23:08.467'
update b
set b.[time]=dateadd(d,1,b.[time])
from @tab2 b
inner join @tab1 a on b.id=a.id
where a.mun2>a.mun1*0.5
select id,[time] from @tab2
/*
id time
----------- -----------------------
1 2013-05-29 01:23:08.467
2 2013-05-28 01:23:08.467
3 2013-05-28 01:23:08.467
4 2013-05-29 01:23:08.467
5 2013-05-28 01:23:08.467
(5 row(s) affected)
*/