diff --git "a/01\347\277\201\347\253\240\345\275\254/\344\275\234\344\270\232/2022-09-20 \345\233\276\344\271\246\346\237\245\350\257\242.md" "b/01\347\277\201\347\253\240\345\275\254/\344\275\234\344\270\232/2022-09-20 \345\233\276\344\271\246\346\237\245\350\257\242.md" new file mode 100644 index 0000000000000000000000000000000000000000..d75c9f8759b19e53d77f966e6bdbb5cfb5e86acd --- /dev/null +++ "b/01\347\277\201\347\253\240\345\275\254/\344\275\234\344\270\232/2022-09-20 \345\233\276\344\271\246\346\237\245\350\257\242.md" @@ -0,0 +1,66 @@ +```sql +--- 创建学生游标,该游标包含(学生姓名,兴趣爱好,生源地,荣誉总数) +declare xs cursor for +(select name,hobby,ori_loca,prize from tb_student +join tb_inf_student on tb_inf_student.stu_num=tb_student.stu_num) +--- 循环遍历161开头的学生信息 +declare xs1 cursor scroll for (select * from tb_student where stu_num like'161%') +open xs1 +declare @num int +declare @name varchar(40) +declare @gender int +declare @birth date +declare @school varchar(40) +declare @major varchar(40) +fetch first from xs1 into @num,@name,@gender,@birth,@school,@major +while @@FETCH_STATUS=0 + begin + print convert(varchar(10),@num)+' '+@name+' '+convert(varchar(10),@gender)+' '+convert(varchar(10),@birth)+' '+@school+@major + fetch next from xs1 into @num,@name,@gender,@birth,@school,@major + end +close xs1 +deallocate xs1 +--- 使用游标统计生源地为北京的荣誉总数 +declare xs2 cursor scroll for (select prize from tb_inf_student where ori_loca='北京') +open xs2 +declare @prize int +declare @sum int=0 +fetch first from xs2 into @prize +while @@FETCH_STATUS=0 + begin + set @sum += @prize + fetch next from xs2 into @prize + end +print @sum +close xs2 +--- 合理使用游标和事务,让5-1号前借书的学生将图书归还 +deallocate xs3 +declare xs3 cursor scroll for (select stu_num,return_time from tb_record where borrow_time<'2019-05-01') +open xs3 +begin transaction +declare @a char(8) +declare @b date +fetch first from xs3 into @a,@b +while @@FETCH_STATUS=0 + begin + if @b is null + begin + update tb_record set return_time = getdate() where stu_num = @a + end + fetch next from xs3 into @a,@b + end +--select * from tb_record +--rollback transaction +declare @err int=0 +set @err +=@@error +if @err>0 + begin + print '失败' + rollback transaction + end +else + begin + select stu_num,return_time from tb_record + end +``` +