游标

--select * from master..sysprocesses
--use test
declare my_cursor cursor scroll dynamic --scroll表示可以向前或向后移动 dynamic:表示可写也可读,
for
SELECT DaoHangMingCheng,DaoHangKey,YeMianMingCheng,KeyString AS YeMianKey FROM dbo.YeMianT --定义my_cursor 游标
open my_cursor --打开游标
declare @DaoHangMingCheng nvarchar(128)--定义一个变量
declare @DaoHangKey varchar(128)--定义一个变量
declare @YeMianMingCheng nvarchar(128)--定义一个变量
declare @YeMianKey varchar(128)--定义一个变量


fetch next from my_cursor into @DaoHangMingCheng,@DaoHangKey,@YeMianMingCheng,@YeMianKey --游标停在第一条记录前面,第一次执行,测试有没有记录存在

while(@@fetch_status=0) --取数据,直到-2即没有记录
begin


INSERT INTO [Tangniaobing].[dbo].[GongNengLieBiaoT]
([CreatedTime]
,[KeyString]
,[GongNengMingCheng]
,[DaoHangMingCheng]
,[DaoHangKey]
,[YeMianMingCheng]
,[YeMianKey]
,[GongNengZiFu])
VALUES(
GETDATE(),
NEWID(),
'Select',
@DaoHangMingCheng,
@DaoHangKey,
@YeMianMingCheng,
@YeMianKey,
'')


INSERT INTO [Tangniaobing].[dbo].[GongNengLieBiaoT]
([CreatedTime]
,[KeyString]
,[GongNengMingCheng]
,[DaoHangMingCheng]
,[DaoHangKey]
,[YeMianMingCheng]
,[YeMianKey]
,[GongNengZiFu])
VALUES(
GETDATE(),
NEWID(),
'Add',
@DaoHangMingCheng,
@DaoHangKey,
@YeMianMingCheng,
@YeMianKey,
'')


INSERT INTO [Tangniaobing].[dbo].[GongNengLieBiaoT]
([CreatedTime]
,[KeyString]
,[GongNengMingCheng]
,[DaoHangMingCheng]
,[DaoHangKey]
,[YeMianMingCheng]
,[YeMianKey]
,[GongNengZiFu])
VALUES(
GETDATE(),
NEWID(),
'Delete',
@DaoHangMingCheng,
@DaoHangKey,
@YeMianMingCheng,
@YeMianKey,
'')


INSERT INTO [Tangniaobing].[dbo].[GongNengLieBiaoT]
([CreatedTime]
,[KeyString]
,[GongNengMingCheng]
,[DaoHangMingCheng]
,[DaoHangKey]
,[YeMianMingCheng]
,[YeMianKey]
,[GongNengZiFu])
VALUES(
GETDATE(),
NEWID(),
'Update',
@DaoHangMingCheng,
@DaoHangKey,
@YeMianMingCheng,
@YeMianKey,
'')


--fetch next from my_cursor
fetch next from my_cursor into @DaoHangMingCheng,@DaoHangKey,@YeMianMingCheng,@YeMianKey
end

close my_cursor
deallocate my_cursor
--SELECT * FROM [GongNengLieBiaoT]

原文地址:https://www.cnblogs.com/rhws/p/4252441.html