0

I am having trouble adding a field to a string. Right now I have a stored procedure running on a giant string (everything inside '') but I am running into problems when creating the Where statement.

I have:

' Cast(Name AS varchar(max)) NOT IN (''Jimmy' + CHAR(39) + 's'')'

But I am getting an error with the CHAR(39). How can I effectively make it look like Jimmy's inside the string? I know it's probably a stupid fix, but please help.

1 Answer 1

10

You need to double it up again since the apostrophe has to survive two rounds of delimiters. Try:

' Cast(Name AS varchar(max)) NOT IN (''Jimmy''''s'')'

For example, compare:

DECLARE @sql NVARCHAR(255) = N'SELECT ''Jimmy' + CHAR(39) + ''';';
EXEC sp_executesql @sql;

Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string 'Jimmy';'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Jimmy';'.

And this:

DECLARE @sql NVARCHAR(255) = N'SELECT ''Jimmy''s'';';
EXEC sp_executesql @sql;

Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string ';'.

Finally:

DECLARE @sql NVARCHAR(255) = N'SELECT ''Jimmy''''s'';';
EXEC sp_executesql @sql;

Result:

-------
Jimmy's
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I tried this but it picks it up as a " instead of a ' =\ I get the error: Unclosed quotation mark after the character string ".
Oh wow never mind, I had an extra Char(39) at the end that was messing it up. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.