iT邦幫忙

0

T-SQL 中字串與變數串接的問題

我現在碰到一個問題需要將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邦的各位要如何改才會正確呢?

1 個回答

6
賽門
iT邦超人 1 級 ‧ 2010-04-30 17:09:35
最佳解答

建議您改成這樣:

<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  
看更多先前的回應...收起先前的回應...
lalelee iT邦新手 4 級 ‧ 2010-04-30 17:36:47 檢舉

轉型的部份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  
lalelee iT邦新手 4 級 ‧ 2010-04-30 17:37:39 檢舉

'restore database xxx' <----- 這句語法有誤

賽門 iT邦超人 1 級 ‧ 2010-04-30 23:49:28 檢舉

抱歉, 記錯EXECUTE語法, 修訂如下:

&lt;pre class="c" name="code">DECLARE @VAR int
DECLARE @Command NVARCHAR(1000)      
SET @VAR = 1   
while(@VAR&lt;=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

<<補充回答有問題, 重新用回應回答>>

lalelee iT邦新手 4 級 ‧ 2010-05-04 10:31:22 檢舉

最後發現需要這樣 :

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

感謝

我要發表回答

立即登入回答