2015-01-17 64 views
0
declare @databasename nvarchar(50), 
     @timestamp nvarchar(50), 
     @sqlcmd nvarchar(1000) 

set @databasename = (select min(name) 
        from sys.databases 
        where name not in ('master','model','tempdb','msdb')) 

while @databasename is not null 
begin 
    set @timestamp = replace(replace(replace(convert(nvarchar,getdate()),' ','_'),':','_'),'-',' ') 
    set @sqlcmd = 'BACKUP DATABASE '[email protected]+' TO DSIK=' + ' C:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup\'+ @databasename +'_'[email protected]+'.bkp' 

    exec (@sqlcmd) 

    set @databasename = (select min(name) 
         from sys.databases 
         where name not in ('master','model','msdb','tempdb') 
          and name > @databasename) 
end; 
go 
+0

請問您能解釋一下您的問題嗎? 你有什麼錯誤? –

回答

0

(1)TO DSIKTO DISK

(2)C:\Prog...部分應該在單引號包圍。所以,你最好使用三個撇號在path + filename開頭和結尾'''C:\Prog...' + ... + ... + '.bkp'''

(3)查詢,正確解析,應該像(不要忘了用正確的路徑替換C:\Prog...部分):

declare 
@databasename nvarchar(50), 
@timestamp nvarchar(50), 
@sqlcmd nvarchar(1000) 
; 
set @databasename= 
(select min(name) from sys.databases 
where name not in ('master','model','tempdb','msdb')) 
; 
while @databasename is not null 
begin 
set @timestamp= replace(replace(replace(convert(nvarchar,getdate()),' ','_'),':','_'),'-',' '); 
set @sqlcmd ='BACKUP DATABASE '[email protected]+' TO DISK=' + '''C:\Prog...' + @databasename +'_'[email protected]+'.bkp'''; 
exec (@sqlcmd); 
set @databasename=(select min(name) from sys.databases where name not in ('master','model','msdb','tempdb')and name > @databasename); 
end 
; 

(4)這是一個很好的做法,以結束每(完整命令)「;」。

相關問題