日期:2014-05-18  浏览次数:20435 次

sql 累加
SQL code

create table T
(
    [1] varchar(10),
    [2] varchar(10),
    [3] varchar(10),
    [4] varchar(10),
    x varchar(10)
);
insert into T
select '0','X','0','2','0'
union
select '1','2','Y','2','0'
union
select '3','X','X','2','0'
union
select '0','Y','1','2','0'

declare @i int,@i_column varchar(10)
set @i=1
set @i_column=''
while @i<=4
    begin
        set @i_column='['+cast(@i as varchar(10))+']'
        update T set x=cast(x as float)+(case when ltrim(rtrim(@i_column))='x' then 1 when ltrim(rtrim(@i_column))='y' then 0.5 else 0 end)
        set @i=@i+1
    end



以上代码update得不到值,改用exec后可以,WHY

------解决方案--------------------
这相当于拼接动态SQL的字符串了,要动态执行。