问题
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