自己写的一个使用游标的小例子
游标因效率低下而为人所诟病,但当我们做很多“一次性”的工作的时候,游标还是很方便地,嘿嘿。刚刚用游标解决了一个实际的问题,记录在下,以后备查,也给想用游标的同志提供一个小例子(注释都删掉了哦,大家关注里面的语法就行了):
1DECLARE product_cursor CURSOR FOR
2SELECT
3 VendeeClassID, UserID, VendeeClassCode
4FROM
5 VendeeClass order by UserID
6
7declare @UserID int
8declare @ClassCode varchar(8)
9declare @VendeeClassID int
10
11declare @globalUserID int
12declare @globalCount int
13declare @globalClassCode varchar(8)
14set @globalUserID = -1
15
16OPEN product_cursor
17FETCH NEXT FROM product_cursor INTO @VendeeClassID, @UserID, @ClassCode
18WHILE @@FETCH_STATUS = 0
19BEGIN
20 if(@globalUserID = @UserID)
21 begin
22 set @globalCount = @globalCount+1
23 if(@globalCount>9)
24 begin
25 set @globalClassCode = '01' + cast(@globalCount as varchar)
26 end
27 else
28 begin
29 set @globalClassCode = '010' + cast(@globalCount as varchar)
30 end
31 if(@ClassCode is null)
32 update VendeeClass set VendeeClassCode=@globalClassCode where VendeeClassID=@VendeeClassID
33 end
34 else
35 begin
36 set @globalUserID = @UserID
37 set @globalCount = 1;
38 if(@ClassCode is null)
39 update VendeeClass set VendeeClassCode='0101' where VendeeClassID=@VendeeClassID
40 end
41
42 FETCH NEXT FROM product_cursor INTO @VendeeClassID, @UserID, @ClassCode
43END
44
45CLOSE product_cursor
46DEALLOCATE product_cursor
2SELECT
3 VendeeClassID, UserID, VendeeClassCode
4FROM
5 VendeeClass order by UserID
6
7declare @UserID int
8declare @ClassCode varchar(8)
9declare @VendeeClassID int
10
11declare @globalUserID int
12declare @globalCount int
13declare @globalClassCode varchar(8)
14set @globalUserID = -1
15
16OPEN product_cursor
17FETCH NEXT FROM product_cursor INTO @VendeeClassID, @UserID, @ClassCode
18WHILE @@FETCH_STATUS = 0
19BEGIN
20 if(@globalUserID = @UserID)
21 begin
22 set @globalCount = @globalCount+1
23 if(@globalCount>9)
24 begin
25 set @globalClassCode = '01' + cast(@globalCount as varchar)
26 end
27 else
28 begin
29 set @globalClassCode = '010' + cast(@globalCount as varchar)
30 end
31 if(@ClassCode is null)
32 update VendeeClass set VendeeClassCode=@globalClassCode where VendeeClassID=@VendeeClassID
33 end
34 else
35 begin
36 set @globalUserID = @UserID
37 set @globalCount = 1;
38 if(@ClassCode is null)
39 update VendeeClass set VendeeClassCode='0101' where VendeeClassID=@VendeeClassID
40 end
41
42 FETCH NEXT FROM product_cursor INTO @VendeeClassID, @UserID, @ClassCode
43END
44
45CLOSE product_cursor
46DEALLOCATE product_cursor