一个并不复杂的问题
zcxc 2003-05-11 09:44:05 有一个aaa表,如:
bh b1 b2 b3 b4
1 12345 12341 null null
2 12344 12345 null null
3 12345 12342 null null
4 12343 12345 null null
5 12345 12343 null null
6 12345 12344 null null
7 12344 12343 null null
8 12344 12321 null null
9 12312 12322 null null
10 12345 12323 null null
11 12321 12344 null null
12 12121 12212 null null
13 12323 12312 null null
b1、b2列可存在相同的数据,要在b1列中找出不同的数据,且要求在b1、b2列数据相同的情况下,在先出现的数据行的b3、b4列分别标上‘1’和bh列的号码,其余b1、b2列中相同的数据在b4列上标上bh列的号码。 可用下面存储过程实现。
CREATE proc cx
as
declare @sz int,@aa int
set @sz=1
select @aa=count(*) from aaa
while @sz<=@aa
begin
if exists (select b1 from aaa where bh=@sz and b3 is null and b4 is null)
begin
update aaa set b3=1 where bh=@sz
update aaa set b4=@sz where b1=(select b1 from aaa where bh=@sz) and b4 is null or b2=(select b1 from aaa where bh=@sz) and b4 is null
end
select @sz=@sz+1
end
return
得到结果如下:
bh b1 b2 b3 b4
1 12345 12341 1 l
2 12344 12345 null 1
3 12345 12342 null 1
4 12343 12345 null 1
5 12345 12343 null 1
6 12345 12344 null 1
7 12344 12343 1 7
8 12344 12321 null 7
9 12312 12322 1 9
10 12345 12323 null 1
11 12321 12344 null 7
12 12121 12212 1 12
13 12323 12312 null 9
问题是在数据量很大时,用while循环逐个查找,挺费时的。有没有更好的方法实现上述要求。