在动态查询字符串sql中使用stuff

时间:2016-09-27 10:16:13

标签: sql sql-server database

我正在尝试使用逗号分隔来获取两列。此代码

SELECT STUFF(( SELECT ',' + Cast(Column1 As varchar(50))+'_'+Cast(Column2 As varchar(50)) FROM Table FOR XML PATH(''), TYPE).value('.', NVARCHAR(MAX)), 1, 1, '') As Result

对我有用。但我需要在动态查询字符串中使用它,当我尝试这样做时会出现错误。

Declare @String AS NVARCHAR(MAX)
Set @string='SELECT STUFF(( SELECT ',' + Cast(Column1 As varchar(50))+'_'+Cast(Column2 As varchar(50)) FROM Table FOR XML PATH(''), TYPE).value('.', NVARCHAR(MAX)), 1, 1, '') As Result'
EXEC sp_executesql @String

1 个答案:

答案 0 :(得分:3)

您需要通过将它们加倍来转义动态SQL中的引号,否则SQL Server认为报价已经结束:

Set @string='SELECT STUFF(( SELECT '','' + Cast(Column1 As varchar(50))+''_''...

http://blog.sqlauthority.com/2008/02/17/sql-server-how-to-escape-single-quotes-fix-error-105-unclosed-quotation-mark-after-the-character-string/