该脚本逐个处理SQL Server数据库备份(通过游标),并在完成所有数据库时发送[success]邮件。
光标代码:
SELECT Name
FROM sys.databases
WHERE Name NOT IN ('Master', 'tempdb')
ORDER BY Name
结果:20个数据库
每天脚本会在完成所有20个数据库后发送成功邮件。 今天,我获得了成功邮件,只完成了9个数据库(但我的SQL Server中仍有20个数据库)。
究竟发生了什么?为什么游标仅用9个DB完成?
脚本逻辑:
IF (@BackupType = 'Differential' OR @BackupType = 'Trxlog')
BEGIN
DECLARE db_cursor CURSOR FOR
SELECT Name
FROM sys.databases
WHERE Name NOT IN ('Master', 'tempdb')
ORDER BY Name
END
ELSE
BEGIN
DECLARE db_cursor CURSOR FOR
SELECT Name
FROM sys.databases
WHERE Name NOT IN ('tempdb')
ORDER BY Name
END
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN
--Code for taking the backup
FETCH NEXT FROM db_cursor INTO @DBName
END
--Code for sending the [Success] mail
--
CLOSE db_cursor
DEALLOCATE db_cursor
答案 0 :(得分:0)
将光标类型更改为LOCAL STATIC
解决了我的问题。
DECLARE db_cursor CURSOR LOCAL STATIC