在SQL Server中,我想清除个人信息并备份它
我完成了1〜5。但找不到办法做6。
我想将bak文件压缩为zip文件。 例如,下面的代码可以在Powershell脚本中使用。有没有办法在SQL脚本中使用此.Net函数?
[System.IO.Compression.ZipFile]::CreateFromDirectory($CurrentPath, $DeployHistoryFilePath)
下面是我的完整剧本。
DECLARE @DBName NVARCHAR(MAX) = N'TestDB'
DECLARE @BackupPath NVARCHAR(MAX) = N'D:\Database\Backup'
EXEC ('master.dbo.xp_create_subdir N'''+ @BackupPath +'''')
DECLARE @BackupName NVARCHAR(MAX) = N'OnCube_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(MAX), GETDATE(), 120), N'-', N''), N':', N''), N' ', N'_')
DECLARE @DiskFile NVARCHAR(MAX) = @BackupPath + N'\' + @BackupName + N'.bak'
BACKUP DATABASE @DBName TO DISK = @DiskFile
DECLARE @SQL NVARCHAR(MAX) = 'SELECT TOP (1) @OriginalMdf = name FROM ' + @DBName + '.sys.database_files WHERE file_id = 1'
DECLARE @OriginalMdf NVARCHAR(MAX)
EXEC sp_executesql @SQL, N'@OriginalMdf NVARCHAR(MAX) OUT', @OriginalMdf out
SET @SQL = 'SELECT TOP (1) @OriginalLdf = name FROM ' + @DBName + '.sys.database_files WHERE file_id = 2'
DECLARE @OriginalLdf NVARCHAR(MAX)
EXEC sp_executesql @SQL, N'@OriginalLdf NVARCHAR(MAX) OUT', @OriginalLdf out
DECLARE @PartialMdf NVARCHAR(MAX) = @BackupPath + N'\' + @BackupName + N'.mdf'
DECLARE @PartialLdf NVARCHAR(MAX) = @BackupPath + N'\' + @BackupName + N'_0.ldf'
RESTORE FILELISTONLY FROM DISK = @DiskFile
RESTORE DATABASE @BackupName
FROM DISK = @DiskFile
WITH MOVE @OriginalMdf TO @PartialMdf,
MOVE @OriginalLdf TO @PartialLdf
EXEC (N'
USE [' + @BackupName + ']
UPDATE Person
SET
PatientNo = NULL
, PatientName = N''Cleared'' + CONVERT(NVARCHAR(MAX), RawID)
, RoomNo = NULL
, BedNo = NULL
, Birthday = NULL
, Sex = NULL
, Address = NULL
, AdmitDate = NULL
, AdmitNo = NULL
, Description = NULL
, DischargedDate = NULL
')
DECLARE @ClearedDiskFile NVARCHAR(MAX) = @BackupPath + N'\' + @BackupName + N'_PatientInfoCleared.bak'
BACKUP DATABASE @BackupName TO DISK = @ClearedDiskFile
EXEC('DROP DATABASE [' + @BackupName + ']')
EXEC ('xp_cmdshell ''del "' + @DiskFile + '"''')
-- I Want to compress bak file to zip here
-- For instance, below code can be used in Powershell script. Is there a way to use this .Net function in SQL script?
-- [System.IO.Compression.ZipFile]::CreateFromDirectory($CurrentPath, $DeployHistoryFilePath)
PRINT N'Success to make ' + @ClearedDiskFile + '. Patient informations are all cleared'
答案 0 :(得分:0)
是否可以在SQL脚本中使用此.Net函数?
是的,您可以将SQL CLR与C#一起使用
查看使用7-zip和SharpZipLib here的示例:
还可以在不使用Powershell脚本的情况下从SQL创建zip文件: Create zip file from SQL Server