2017-10-06 84 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