我現在碰到一個問題需要將300多個資料庫備份檔案還原,這300多個db的名稱如下
xxx001
xxx002
xxx003
.
.
.
xxx300
於是寫了底下的T-SQL:
DECLARE @VAR int=1
while(@VAR<=300)
BEGIN
'restore database xxx00'+ CAST(@VAR AS text)+
'from disk = H:\MSSQL10.COASQL_2\MSSQL\Backup\xxx00'
+ CAST(@VAR AS text) +'.BAK'
set @VAR+=1
END
但是在變數轉型和串接的部分有語法上的錯誤,請問IT邦的各位要如何改才會正確呢?
建議您改成這樣:
<pre class="c" name="code">DECLARE @VAR int
SET @VAR = 1
while(@VAR<=300)
BEGIN
execute 'restore database xxx'+ RIGHT(STR(1000+@VAR), 3)+
' from disk = H:\MSSQL10.COASQL_2\MSSQL\Backup\xxx'
+ RIGHT(STR(1000+@VAR), 3) +'.BAK'
set @VAR=@VAR+1
END
轉型的部份OK了!
但是這段粗體部分,還是顯示語法有誤...
<pre class="c" name="code">DECLARE @VAR int
SET @VAR = 1
while(@VAR<=300)
BEGIN
execute <strong>'restore database xxx'</strong>'restore database xxx'+ RIGHT(STR(1000+@VAR), 3)+
' from disk = H:\MSSQL10.COASQL_2\MSSQL\Backup\xxx'
+ RIGHT(STR(1000+@VAR), 3) +'.BAK'
set @VAR=@VAR+1
END
'restore database xxx' <----- 這句語法有誤
抱歉, 記錯EXECUTE語法, 修訂如下:
<pre class="c" name="code">DECLARE @VAR int
DECLARE @Command NVARCHAR(1000)
SET @VAR = 1
while(@VAR<=300)
BEGIN
SET @Command = 'restore database xxx' + RIGHT(STR(1000+@VAR), 3)+
' from disk = H:\MSSQL10.COASQL_2\MSSQL\Backup\xxx'
+ RIGHT(STR(1000+@VAR), 3) +'.BAK'
execute (@Command)
set @VAR=@VAR+1
END
<<補充回答有問題, 重新用回應回答>>
最後發現需要這樣 :
DECLARE @VAR int
DECLARE @Command NVARCHAR(1000)
SET @VAR = 1
while(@VAR<=300)
BEGIN
SET @Command = 'restore database xxx' + right('000' + cast(@VAR as varchar),3)+
' from disk = ''H:\MSSQL10.COASQL_2\MSSQL\Backup\xxx'+ Right('000' + cast(@VAR as varchar),3) +'.BAK'''
execute (@Command)
set @VAR=@VAR+1
END
感謝