2017-10-06 86 views
1

我想替換動態SQL中的select語句中的字符串的一部分,但我收到錯誤。SQL Server 2012替換動態sql中的Select語句中的字符串

這裏是我的代碼:

set @oldTblPrefix = 'ABC' 
set @newTblPrefix = 'XYZ' 
set @sourcetid = 17 
set @template =' 
INSERT INTO ' [email protected] + '.[Tforms] 
      (id 
      ,[tablename]) 

    select id, 
      replace([tablename],'[email protected]+','[email protected]+') 
    from '+ @DB+ '.[Tforms] where tid=' +str(@sourcetid) 
exec sp_Executesql @template 

但我收到這些錯誤:

無效的列名 'ABC'。無效的列名稱'XYZ'。

回答

0

您需要在變量前後添加單引號 - 每邊兩個 - 。一個在結果字符串中顯示,另一個在轉義字符中顯示

用末尾的print替換execute,直到找到它,並檢查結果查詢是否正確。

set @template =' 
INSERT INTO ' [email protected] + '.[Tforms] 
      (id 
      ,[tablename]) 

    select id, 
      replace([tablename],'''[email protected]+''','''[email protected]+''') 
    from '+ @DB+ '.[Tforms] where tid=' +str(@sourcetid) 
PRINT @template 
--exec sp_Executesql @template