diff --git "a/42\345\217\267\345\224\220\347\232\223\351\242\226/30\346\227\245\347\254\224\350\256\260.md" "b/42\345\217\267\345\224\220\347\232\223\351\242\226/30\346\227\245\347\254\224\350\256\260.md" new file mode 100644 index 0000000000000000000000000000000000000000..659e71edc8fac32def9d254725754ab54a29c7a7 --- /dev/null +++ "b/42\345\217\267\345\224\220\347\232\223\351\242\226/30\346\227\245\347\254\224\350\256\260.md" @@ -0,0 +1,30 @@ + +什么是游标 +游标(Cursor)它使用户可逐行访问由SQL Server返回的结果集。使用游标(cursor)的一个主要的原因就是把集合操作转换成单个记录处理方式。用SQL语言从数据库中检索数据后,结果放在内存的一块区域中,且结果往往是一个含有多个记录的集合。游标机制允许用户在SQL server内逐行地访问这些记录,按照用户自己的意愿来显示和处理这些记录。 + +游标分类: + +(1)静态游标(Static):在操作游标的时候,数据发生变化,游标中数据不变 (2)动态游标(Dynamic):在操作游标的时候,数据发生变化,游标中数据改变,默认值。 (3)键集驱动游标(KeySet):在操作游标的时候,被标识的列发生改变,游标中数据改变,其他列改变,游标中数据不变。 + +游标的使用 +创建游标: + +--1.创建游标(Scroll代表滚动游标,不加Scroll则是只进的,只能支持fetch next) +declare <游标名> cursor scroll for select stuname from stuinfo +打开游标: + +open <游标名> +关闭游标: + +close <游标名> +释放游标: + +deallocate <游标名> +提取数据操作: + +fetch first from <游标名> --结果集的第一行 +fetch last from <游标名> --最后一行 +fetch absolute 1 from <游标名> --从游标的第一行开始数,第n行。 +fetch relative 3 from <游标名> --从当前位置数,第n行。 +fetch next from <游标名> --当前位置的下一行 +fetch prior from <游标名> --当前位置的上一行 \ No newline at end of file diff --git "a/42\345\217\267\345\224\220\347\232\223\351\242\226/\345\224\220\347\232\223\351\242\22630\346\227\245 .sql" "b/42\345\217\267\345\224\220\347\232\223\351\242\226/\345\224\220\347\232\223\351\242\22630\346\227\245 .sql" new file mode 100644 index 0000000000000000000000000000000000000000..88e1defc0da0b4f870c5cce62b905a1b68828560 --- /dev/null +++ "b/42\345\217\267\345\224\220\347\232\223\351\242\226/\345\224\220\347\232\223\351\242\22630\346\227\245 .sql" @@ -0,0 +1,49 @@ +--ʹαʵּн +declare huhu cursor scroll +for select * from People +open huhu +declare @PeopleId int +fetch first from huhu into @PeopleId +while (@@FETCH_STATUS=0) + begin + update People set PeopleSalary+=1000 where PeopleId=@PeopleId + fetch next from huhu into @PeopleId + end +close huhu +deallocate huhu +select * from People +--ʹαɾԱ +declare huhu cursor scroll +for select * from People +open huhu +declare @id int +fetch first from huhu into @id +while (@@FETCH_STATUS=0) + begin + declare @money int=(select PeopleSalary from People where PeopleId=@id) + + if(@money<5000) + begin + delete People where PeopleId = @id + end + fetch next from huhu into @id + end +close huhu +deallocate huhu +select * from People +--ʹα ʵ:ABIDֵֶͬôBеʡݣ ޸ijAеijһ£ +declare cur_id cursor scroll +for select A.* from A inner join B on A.id = B.id +open cur_id +declare @id int , @id1 int,@Province varchar(10),@City varchar(10) +fetch first from cur_id into @id,@Province,@City +while(@@FETCH_STATUS = 0) + begin + update B set B.Province = @Province , B.City = @City where B.id = @id + fetch next from cur_id into @id,@Province,@City + end + +close cur_id +deallocate cur_id +select * from A +select * from Bt \ No newline at end of file