sql server 游标使用
--------------------利用游标对查询的数据集进行遍历-----------------------
DECLARE @gcode VARCHAR(10) ,@name VARCHAR(50),@price CHAR(10)
DECLARE sel CURSOR SCROLL FOR
SELECT c_gcode,c_name,c_price FROM tb_gds
WHERE c_gcode IN ('000001','000002','000003')
ORDER BY c_gcode;
OPEN sel
FETCH NEXT FROM sel INTO @gcode,@name,@price
WHILE @@FETCH_STATUS=0
BEGIN
PRINT '商品编码:'+@gcode
PRINT '商品名称:'+@name
PRINT '商品价格:'+@price
PRINT '................'
FETCH NEXT FROM sel INTO @gcode,@name,@price
END
CLOSE sel
DEALLOCATE sel
-------------------利用游标修改、删除数据--------------------------
BEGIN TRAN
DECLARE update_gdsstore CURSOR SCROLL FOR
SELECT c_gcode,c_price,c_store_id
FROM dbo.tb_gdsstore
WHERE c_gcode IN ('000001','000002','000003') FOR UPDATE OF c_price
OPEN update_gdsstore
DECLARE @ROWCOUNT INT
SET @rowcount=1
FETCH ABSOLUTE @rowcount FROM update_gdsstore
UPDATE dbo.tb_gdsstore SET c_price='12' WHERE CURRENT OF update_gdsstore
SET @ROWCOUNT=@ROWCOUNT+1
FETCH NEXT FROM update_gdsstore
UPDATE dbo.tb_gdsstore SET c_price='11' WHERE CURRENT OF update_gdsstore
SET @ROWCOUNT=@ROWCOUNT+1
FETCH NEXT FROM update_gdsstore
UPDATE dbo.tb_gdsstore SET c_price='10' WHERE CURRENT OF update_gdsstore
CLOSE update_gdsstore
DEALLOCATE update_gdsstore
ROLLBACK
-----------------------------利用游标对查询的数据集进行遍历-------------------------------
DECLARE @ggcode VARCHAR(10),@gname VARCHAR(50),@produce VARCHAR(30)
DECLARE get_info CURSOR SCROLL FOR
SELECT c_gcode,c_name,c_produce FROM tb_gds
WHERE c_adno='201'
ORDER BY c_gcode;
OPEN get_info
FETCH NEXT FROM get_info INTO @ggcode,@gname,@produce
WHILE @@FETCH_STATUS=0
BEGIN
PRINT '商品编码:'+@ggcode
PRINT '商品名称:'+@gname
PRINT '商品产地:'+@produce
PRINT '................'
FETCH NEXT FROM get_info INTO @ggcode,@gname,@produce
END
CLOSE get_info
DEALLOCATE get_info