Adding an apostrophe into a dynamic SQL

限于喜欢 提交于 2019-12-11 15:17:28

问题


I would like to ask how can I add an apostrophe into a dynamic SQL. I need to return an SQL statement in one of the columns which has to have apostrophes in itself.

I have the following statement:

SET @SQL_String = N'INSERT INTO #ReturnTable
    (
    TableName,
    ColName,
    SQL_Statement,
    Value
     )
VALUES
    (
    ''' + @TableName + ''',
    ''' + @ColName + ''',
    ''' +
         'SELECT ' + 
             @ColName +
         ' FROM ' +
             @TableSchema + '.' + @TableName +
         ' WHERE ' + 
             @ColName + ' = ' + CAST(@GuidArgument AS NVARCHAR(50)) + ';' +''',
        (
        SELECT
            ' + @ColName + '
        FROM
            ' + @TableSchema + '.' + @TableName +
       ' WHERE '
            + @ColName + ' = ''' + CAST(@GuidArgument AS NVARCHAR(50)) + 
       '''))';

Executing with:

EXECUTE @RC = [dbo].[GetLocationOfGuidPre] 'F2CAB996-F00F-43B8-A67A-0000721A829D'

I need to put a whole first CAST into a pair of '.

I've tried:

  • Putting whole CAST statement into a separeted variable like: DECLARE @Test NVARCHAR(50);
    • SET @Test = CAST(@GuidArgument AS NVARCHAR(50));
    • SET @Test = 'CAST(@GuidArgument AS NVARCHAR(50))';
    • SET @Test = '''CAST(@GuidArgument AS NVARCHAR(50))''';
  • Addidng two more apostrophes:
    • ' WHERE ' + @ColName + ' = ''' + CAST(@GuidArgument AS NVARCHAR(50)) + ''';'

回答1:


Please use CHAR(39) instead of typing ' in your dynamic code directly. Example:

declare @my_dynamic_sql nvarchar(max) = 'print char(39);';
exec(@my_dynamic_sql);


来源:https://stackoverflow.com/questions/51888923/adding-an-apostrophe-into-a-dynamic-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!