Karl
Karl

Reputation: 1317

SQL ' ' do not get escaped

I am trying to run a query in SQL 2008 by doing:

@query varchar(max)

SET @query = 'SELECT * FROM Table WHERE [Name] = ' 'Karl' ' '

EXEC(@query)

The problem is that for some reason the apostrophes around 'Karl' don't get escaped, i.e. the query executes as ...WHERE [Name] = Karl and fails.

Anyone has a suggestion?

Upvotes: 6

Views: 12031

Answers (7)

Magnus Lindhe
Magnus Lindhe

Reputation: 7317

This works on my machine from SQL Server Management Studio:

@query varchar(max)

SET @query = 'SELECT * FROM Table WHERE [Name] = ''''''Karl'''''''

EXEC(@query)

Upvotes: 2

BlueMonkMN
BlueMonkMN

Reputation: 25601

This works:

create table #demo([Name] varchar(max))
insert into #demo([Name]) values('''Karl''')
insert into #demo([Name]) values('Karl')
declare @query varchar(max)
set @query = 'SELECT * FROM #demo WHERE [Name] = ''''''Karl'''''''
EXEC(@query)

Output:

'Karl'

But if 'Karl' is variable text, it's highly recommended to use something like this instead:

declare @query nvarchar(max)
declare @param varchar(max)
set @param = N'''Karl'''
set @query = N'SELECT * FROM #demo WHERE [Name] = @param'
exec sp_executesql @query, N'@param varchar(max)', @param

Upvotes: 0

Matt Brunell
Matt Brunell

Reputation: 10389

A double single ('') quote will act like a single single quote when inside a string literal.

Have you tried using a variable?

declare @karl_name varchar(10);
set @karl_name = '''Karl''';

SELECT * FROM Table WHERE [Name] = @karl_name

Upvotes: 1

KM.
KM.

Reputation: 103579

Try:

DECLARE @query varchar(max)

SET @query = 'SELECT * FROM Table WHERE [Name] = ''Karl'''

PRINT 'when in doubt, print the query out: '+ISNULL(@query,'')
EXEC(@query)

To have a single quote appear, you need to have two adjacent single quotes. You escape a single quote with a single quote, for example:

PRINT ''''     --will print a one single quote
PRINT ''''''   --will print two single quotes
PRINT 'can''t' --will print can't

Upvotes: 2

John Sansom
John Sansom

Reputation: 41819

There are several ways that you can escape character data in SQL Server, some people even advocate the use of the QUOTENAME() functions.

If you really want to develop of solid understanding of this subject area then may I recommend that you take a look at what experienced SQL Server Developers consider to be essential reading with regard to the different methods you can use to incorporate Dynamic T-SQL into your coding.

The Curse and Blessings of Dynamic SQL

Upvotes: 3

Carlos
Carlos

Reputation: 2923

Simply escape the apostrophes by using the escaping bar \ like this 'SELECT * FROM Table WHERE [Name] = ' \'Karl\' ' '

Hope it helps

Upvotes: -1

KuldipMCA
KuldipMCA

Reputation: 3149

do like this SET @query = 'SELECT * FROM Table WHERE [Name] = ''''Karl'''''

Upvotes: 0

Related Questions