1. CURSOR là gì? Trong c# khi duyệt dữ liệu ta có vòng lặp while, for, do while,.. để duyệt dữ liệu mảng, còn trong SQL Server ta dó vòng lặp Coursor while để duyệt dữ liệu mảng. Coursor trong SQL Server 2. Cách sử dụng vong lặp Coursor Xem qua ví dụ và đọc chú giải dưới để hiểu rõ hơn. Mã: declare mycs cursor for select col1,col2 from tbl_mytable open mycs declare @mycol1 nvarchar(100) declare @mycol2 nvarchar(100) fetch next from mycs into @mycol1,@mycol2 while @@FETCH_STATUS=0 begin delete tbl_mytable2 where coltb2=@mycol1 and coltb3=@mycol2 fetch next from mycs into @mycol1,@mycol2 end close mycs deallocate mycs Chú giải: Câu lệnh dưới nghĩa là : tạo mới 1 cursor với tên mycs và gán toàn bọ dữ liệu tại câu lệnh select cho cursor này. Mã: declare mycs cursor for select col1,col2 from tbl_mytable Mở cursor lên Mã: open mycs Khai báo biến để lấy dữ liệu khi chạy vòng lặp cursor. Mã: declare @mycol1 nvarchar(100) declare @mycol2 nvarchar(100) Chạy cursor khi nào dữ liệu =0 thì thôi, mỗi lần chạy dữ liệu sẽ được gắn cho các biên @mycol1,@mycol2 theo các thứ tự trên mới select tưng ứng : @mycol1=col1, @mycol2=col2 Mã: fetch next from mycs into @mycol1,@mycol2 while @@FETCH_STATUS=0 Thực thi các câu lệnh trong vòng lặp, ví dụ dưới ta thực hiện lệnh delete 1 table với giá trị tương ứng,... Sau khi thực hiện lệnh xong, ta tiếp tục duyệt tiếp dữ liệu bằng câu lệnh: fetch next from .... into..... Mã: begin delete tbl_mytable2 where coltb2=@mycol1 and coltb3=@mycol2 fetch next from mycs into @mycol1,@mycol2 end Đóng cursor lại bằng lệnh : close .... Giải phóng cursor khỏi bộ nhớ bằng lệnh : deallocate .... Mã: close mycs deallocate mycs