Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using single quote in an Exec statement in SQL

I am having issues executing a SQL statement from a stored proc having single quotes. Here is my query from a stored procedure that I am executing.

EXEC('UPDATE myTABLE 
         SET myCOLUMN = (SELECT Replace('OSINGLEQUOTEJOHN DOE','SINGLEQUOTE','''')')

I am trying to update table "myTABLE" column "myCOLUMN" with a value "O'John Doe"

The actual query is like this, i tried to simplify it a bit in the above example

EXEC('UPDATE myTABLE 
         SET myCOLUMN = (SELECT Replace('+ @IntegrationGuardian2FullName +','SINGLEQUOTE','''')')

The value of @IntegrationGuardian2FullName is "OSINGLEQUOTEJOHN DOE". Hope that makes more sense.

Can any body help me formatting this query?

like image 745
Mithil Avatar asked Jul 29 '10 15:07

Mithil


People also ask

How do I run a single quote in SQL?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.

How can I use single quotes in dynamic SQL?

If one single quote denotes the start of the string, and one denotes the end, there's nothing in the middle. If you want one in the middle you might need to have ''' . use backslashes to escape: ...


1 Answers

Use:

EXEC('UPDATE myTABLE 
        SET myCOLUMN = (SELECT REPLACE(''OSINGLEQUOTEJOHN DOE'',
                                       ''SINGLEQUOTE'',
                                       ''''''''))')

What you provided needed two single quotes around the string, and what to replace, and additional single quotes because of the single quote escaping necessary for dynamic SQL.

like image 191
OMG Ponies Avatar answered Oct 27 '22 07:10

OMG Ponies