--将A表的C列更新为B表的效果 declare @tb table([a] int,[b] int,[c] int) insert @tb([a],[b]) select 1,12 union all select 1,13 union all select 1,23 union all select 0,14 union all select 0,15 union all select 1,16 union all select 0,23 union all select 0,22 union all select 1,21 union all select 1,12 /*--A表 select * from @tb ----------------------- a b c ----------- ----------- ----------- 1 12 NULL 1 13 NULL 1 23 NULL 0 14 NULL 0 15 NULL 1 16 NULL 0 23 NULL 0 22 NULL 1 21 NULL 1 12 NULL (所影响的行数为 10 行) */ /* --B表 a b c ----------- ----------- ----------- 1 12 1 1 13 2 1 23 3 0 14 1 0 15 2 1 16 1 0 23 1 0 22 2 1 21 1 1 12 2 */ -->SQL查询如下: -- 法一: declare @j int,@i int update @tb set c = @j, @j = case when @i = a then @j +1 else 1 end, @i = a select * from @tb --法二: declare @j int,@i int update @tb set c = @j, @j = case when @i <> a then 1 else isnull(@j,0)+1 end, @i=a select * from @tb --结果 /* a b c ----------- ----------- ----------- 1 12 1 1 13 2 1 23 3 0 14 1 0 15 2 1 16 1 0 23 1 0 22 2 1 21 1 1 12 2 (所影响的行数为 10 行) */ ------------------------------------------- --将下表的null值用id相同的非null值来填充: declare @tb table (id int,value varchar(2)) insert @tb select 1,'a' union all select 1,'a' union all select 1,null union all select 2,'b' union all select 2,'b' union all select 2,null -->sql查询如下: declare @s varchar(20); update @tb set @s = isnull(value,@s), value = @s; select * from @tb; /* id value ----------- ----- 1 a 1 a 1 a 2 b 2 b 2 b (所影响的行数为 6 行) */
通过变量逐行更新实例
最新推荐文章于 2024-08-13 16:59:41 发布