使用 Alter Database 选项创建过程

Create a procedure with Alter Database option

我有超过 30 个数据库是用 TDE 加密的。现在我必须在不加密的情况下备份每个数据库。 需要以下步骤: - 关闭加密 - 对该数据库进行完整备份 - 将加密设置为

(对不起,我不太会编码)

这是我到目前为止所做的一个例子:

use [Testt]
ALTER DATABASE [Testt] 
SET ENCRYPTION OFF
Go


BACKUP DATABASE [Testt] 
TO  DISK = N'J:\Backup\Testt_full.bak ' WITH NOFORMAT,COPY_ONLY, NOINIT,  
NAME = N'J:\Testt', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO 

GO
use [Testt]
ALTER DATABASE [Testt] 
SET ENCRYPTION ON
GO

对于 30 dbs,有没有更简单的方法来做到这一点?我想到了一个过程或游标

在#tmp 中存储您的数据库名称

DECLARE @dbName nvarchar(MAX) =''
DECLARE @sql nvarchar(MAX) = ''

DECLARE Crs CURSOR LOCAL FOR 
SELECT data
FROM #tmp 


OPEN Crs 
FETCH NEXT FROM Crs into @dbName 

WHILE @@FETCH_STATUS = 0

BEGIN



SET @sql= 'use' + @dbName +
'ALTER DATABASE' + @dbName +
'SET ENCRYPTION OFF'

EXEC(@sql)

DECLARE @dName nvarchar(MAX) = 'J:\' + @dbName 
DECLARE @dPath nvarchar(MAX) = 'J:\Backup\' + @dbName + '_full.bak'

SET @sql='BACKUP DATABASE ' + @dbName +
'TO  DISK = '+ @dPath +' WITH 
NOFORMAT,COPY_ONLY, NOINIT,  
NAME = '+ @dName  +', SKIP, NOREWIND, NOUNLOAD,  STATS = 10'

EXEC(@sql)

SET @sql= 'use  ' + @dbName +
'ALTER DATABASE  ' + @dbName +
'SET ENCRYPTION ON'

 EXEC(@sql)

FETCH NEXT FROM Crs into @dbName 


END


CLOSE Crs

DEALLOCATE Crs          

感谢 Claudio Biselli 的帮助:

我调整了你的光标部分:

DECLARE @dbName nvarchar(MAX) =''
DECLARE @sql nvarchar(MAX) = ''
DECLARE @sql2 nvarchar(MAX) = ''
DECLARE @sql3 nvarchar(MAX) = ''

DECLARE Crs CURSOR LOCAL FOR 
SELECT d.name
FROM sys.databases d
INNER JOIN
sys.dm_database_encryption_keys e ON d.database_id = e.database_id
where d.name not like 'tempdb'

OPEN Crs 
FETCH NEXT FROM Crs into @dbName 

WHILE @@FETCH_STATUS = 0

BEGIN


SET @sql= 'use ' + @dbName +
' ALTER DATABASE ' + @dbName + ' SET ENCRYPTION OFF'
select @sql


SET @sql2='BACKUP DATABASE ' + @dbName +
' TO  DISK = ''J:\Backup\' + @dbName + '_full.bak'' WITH NOFORMAT, COPY_ONLY, NOINIT, NAME = ''J:\'+ @dbName + ''', SKIP, NOREWIND, NOUNLOAD, STATS = 10'
select @sql2


SET @sql3= 'use ' + @dbName +
' ALTER DATABASE ' + @dbName + ' SET ENCRYPTION ON'
select @sql3

FETCH NEXT FROM Crs into @dbName 
END
CLOSE Crs
DEALLOCATE Crs

而且有效:)