查询出所有job名称
select name from IBDMMSQL.msdb.dbo.sysjobs where enabled=1 and name not like ‘Database%’ and name not like ‘DB%’ order by 1
把job名称当成第二个字段的value值(如下的’job_name’)插入[jobs].[Settings]
insert into [jobs].[Settings] values (3008,‘job_name’,null,null,GETDATE(),‘Lukes Liao’,null,null)
把[jobs].[Settings]新增的SettingID(自增长字段)当成第一个字段value值(如下的172)插入[jobs].[Subscriptions]
insert into [jobs].[Subscriptions] values(172,‘Programming@willi.com’)
insert into [jobs].[Subscriptions] values(172,‘DBA@will.com’)
写法
游标1:把job名称当成第二个字段的value值插入[jobs].[Settings]
DECLARE @jobname varchar(200) --声明变量,用户接收循环时的变量
DECLARE RunPerRow CURSOR FOR --定义游标
select name from IBDMMSQL.msdb.dbo.sysjobs where enabled=1 and name not like 'Database%' and name not like 'DB%' and name not in ('sp_purge_jobhistory','syspolicy_purge_history') order by 1
OPEN RunPerRow --打开游标
FETCH NEXT FROM RunPerRow into @jobname --从游标里取出数据赋值到声明的变量中
while @@FETCH_STATUS = 0 --返回被FETCH语句执行的最后游标的状态,0表示fetch语句成功,1表示fetch语句失败,2表示被提取的行不存在
begin
insert into [jobs].[Settings] values (2994,@jobname,null,null,GETDATE(),'Lukes Liao',null,null)
print 'The cursor successfully fetched a row'
print @jobname
FETCH NEXT FROM RunPerRow into @jobname --转到下一个游标,没有会死循环
end
CLOSE RunPerRow --关闭游标
DEALLOCATE RunPerRow --撤销游标
游标2:把[jobs].[Settings]新增的SettingID(自增长字段)当成第一个字段value值插入[jobs].[Subscriptions]
DECLARE @SettingID int --声明变量,用户接收循环时的变量
DECLARE RunPerRow CURSOR FOR --定义游标
select SettingID from [jobs].[Settings] where SettingID>172 order by 1
OPEN RunPerRow --打开游标
FETCH NEXT FROM RunPerRow into @SettingID --从游标里取出数据赋值到声明的变量中
while @@FETCH_STATUS = 0 --返回被FETCH语句执行的最后游标的状态,0表示fetch语句成功,1表示fetch语句失败,2表示被提取的行不存在
begin
insert into [jobs].[Subscriptions] values(@SettingID,'Programming@will.com')
insert into [jobs].[Subscriptions] values(@SettingID,'DBA@will.com')
print 'The cursor successfully fetched a row'
print @SettingID
FETCH NEXT FROM RunPerRow into @SettingID --转到下一个游标,没有会死循环
end
CLOSE RunPerRow --关闭游标
DEALLOCATE RunPerRow --撤销游标