声明游标 :
DECLARE My_Cursor CURSOR --定义游标
FOR ( SELECT device_id, material_id FROM [dbo].[tablename] )
打开游标 :
OPEN My_Cursor;--打开游标
读取游标元素游:
FETCH NEXT FROM My_Cursor INTO @DeviceID,@MaterialID;--读取第一行数据
关闭游标 :
CLOSE My_Cursor;--关闭游标
释放游标 :
DEALLOCATE My_Cursor;--释放游标
例子
DECLARE @DeviceID bigint,@MaterialID bigint
DECLARE My_Cursor CURSOR --定义游标
FOR ( SELECT device_id, material_id FROM [dbo].[tablename] )
OPEN My_Cursor;--打开游标
FETCH NEXT FROM My_Cursor INTO @DeviceID,@MaterialID;--读取第一行数据
WHILE
--这里对游标的状态进行判断,如果为0,证明游标中有值
@@FETCH_STATUS = 0 BEGIN
UPDATE tablename
SET device_code = ( SELECT code FROM tablename1 WHERE id = @DeviceID ),
material_code = ( SELECT code FROM tablename2 WHERE id =@MaterialID )
WHERE
CURRENT OF My_Cursor;--更新
--读取下一行数据
FETCH NEXT
FROM
My_Cursor INTO @DeviceID,@MaterialID;
END CLOSE My_Cursor;--关闭游标
DEALLOCATE My_Cursor;--释放游标