Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Escape ' '

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?

like image 525
Karl Avatar asked Jun 30 '09 06:06

Karl


2 Answers

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

like image 131
John Sansom Avatar answered Nov 07 '22 19:11

John Sansom


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
like image 2
KM. Avatar answered Nov 07 '22 17:11

KM.