SQL server 游标使用实例
--创建一个游标 DECLARE my_cursor CURSOR FOR SELECT id, Bran_number, Bran_taxis FROM dbo.Base_Branch; --打开游标 OPEN my_cursor; DECLARE @id INT; DECLARE @Bran_taxis VARCHAR(100); DECLARE @bran_number VARCHAR(100); DECLARE @tagint INT; SET @tagint=1; --循环游标 FETCH NEXT FROM my_cursor INTO @id, @bran_number, @Bran_taxis; --获取my_cursor的下一条数据 WHILE @@FETCH_STATUS=0 BEGIN PRINT(@tagint); UPDATE dbo.Base_Branch SET Bran_taxis=@tagint, Bran_SonCount=(SELECT COUNT(*)FROM dbo.Base_Worker WHERE Worker_department=@bran_number) WHERE id=@id; SET @tagint=@tagint+1; FETCH NEXT FROM my_cursor INTO @id, @bran_number, @Bran_taxis; --获取下一条数据并赋值给变量 END; --关闭释放游标 CLOSE my_cursor; DEALLOCATE my_cursor;