表test中有单个字段A,B,C,以A的某一值Value(A)为划分线,小于Value(A)的为旧数据Old(test),大于等于Value(A)的为新数据New(test),如果New(test)中的字段B存在数据行NewRow(test)和Old(test)中字段B相等的数据行OldRow(test),则将OldRow(test)的字段C 赋值到为NewRow (test)的C字段中,当不存在相等数据行时,让New(test)的数据行的C字段从 1 开始取值至数据行结束。
例: 执行前test表值:
A B C
1 1 1
2 2 2
3 3 3
4 4 0
5 1 0
6 6 0
7 2 0
8 4 0
9 9 0
执行后test表值:
A B C
1 1 1
2 2 2
3 3 3
4 4 1
5 1 1
6 6 2
7 2 2
8 4 4
9 9 3
×表中以字段A的值等于4来划分,横线以上为Old(test),以下为New(test)。
其SQL语句如下:
declare @A int , @B int, @NumCount int
set @NumCount = 1
declare myCursor cursor for select A, B from test where A >= 4
open myCursor
fetch next from myCursor into @A, @B
while @@fetch_status = 0
begin
If Exists (select C from test where A < 4 And B = @B)
begin
update test set C = (select C from test where A < 4 And B = @B) where A = @A
end
Else
begin
update test set C = @NumCount where A = @A
set @NumCount = @NumCount + 1
end
fetch next from myCursor into @A, @B
end
close myCursor
deallocate myCursor
外附表创建的SQL语句:
create table test
(A int not null primary key,
B int not null ,
C int null )
insert into test values(1,1,1)
insert into test values(2,2,2)
insert into test values(3,3,3)
insert into test values(4,4,0)
insert into test values(5,1,0)
insert into test values(6,6,0)
insert into test values(7,2,0)
insert into test values(8,4,0)
insert into test values(9,9,0)
OK!至此结束。