简体   繁体   English

SQL Server 数据库备份脚本:如何使用文件路径/位置参数?

[英]SQL Server database backup script: How to use parameters for file path/location?

I use a simple script to backup database in SQL Server:我使用一个简单的脚本来备份 SQL Server 中的数据库:

BACKUP DATABASE AdventureWorks
TO DISK = 'C:\AdventureWorks.BAK'
GO

My goal is to backup several databases using a script.我的目标是使用脚本备份多个数据库。

This will be used to different clients so I have use parameters that I can edit every time I need to run the script.这将用于不同的客户端,因此我使用了每次需要运行脚本时都可以编辑的参数。

SQL Server says that my script has a syntax error. SQL Server 说我的脚本有语法错误。

Can you guys check my query, please?你们可以检查我的查询吗?

declare @loc nvarchar(200) = 'D:\BAK\'
declare @client nvarchar(50) = 'CLIENT001_'
declare @date nvarchar(50) = '2020-02-29'

BACKUP DATABASE DB1
TO DISK = @loc + @client + 'DB1_' + @date + '.BAK'
GO

BACKUP DATABASE DB2
TO DISK = @loc + @client + 'DB2_' + @date + '.BAK'
GO

BACKUP DATABASE DB3
TO DISK = @loc + @client + 'DB3' + @date + '.BAK'
GO

BACKUP DATABASE DB4
TO DISK = @loc + @client + 'DB4' + @date + '.BAK'
GO

You can use dynamic SQL to achieve that.您可以使用动态 SQL 来实现这一点。 Also, GO limits the scope of variables (use only one at the end of the batch).此外, GO限制了变量的范围(在批处理结束时只使用一个)。

declare @loc nvarchar(200) = 'D:\BAK\'
declare @client nvarchar(50) = 'CLIENT001_'
declare @date nvarchar(50) = '2020-02-29'

exec(' BACKUP DATABASE DB1 TO DISK = '''+@loc + @client + 'DB1_' + @date + '.BAK'+''' ')
exec(' BACKUP DATABASE DB2 TO DISK = '''+@loc + @client + 'DB2_' + @date + '.BAK'+''' ')
exec(' BACKUP DATABASE DB3 TO DISK = '''+@loc + @client + 'DB3_' + @date + '.BAK'+''' ')
exec(' BACKUP DATABASE DB4 TO DISK = '''+@loc + @client + 'DB4_' + @date + '.BAK'+''' ')
go

You could also add databases to backup in your dynamic script like below:您还可以在动态脚本中添加要备份的数据库,如下所示:

declare @loc nvarchar(200) = 'D:\BAK\'
declare @client nvarchar(50) = 'CLIENT001_'
declare @date nvarchar(50) = '2020-02-29'
DECLARE @dbs_to_backup VARCHAR(1000)= 'DB1,DB2,DB3,DB4';
DECLARE @final_loc2 NVARCHAR(500)= @date + '.BAK';

drop table if exists #temp

SELECT replace(final_string, '##', value) string_to_execute, ROW_NUMBER() over (order by (select null)) rn
into #temp
FROM
(
    SELECT 'BACKUP DATABASE ## TO DISK = ''' + @loc + '##_' + @final_loc2 + '''' final_string
) t
CROSS APPLY
(
    SELECT value
    FROM STRING_SPLIT(@dbs_to_backup, ',')
) tt;

declare @i int = 1
declare @sql nvarchar(1000)

while ((select max(rn) from #temp) >= @i)
begin
    set @sql = (select string_to_execute from #temp where rn = @i)
    print @sql
    exec sp_executesql @sql
    set @i += 1
end

HTH.哈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM