问题
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?
回答1:
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.
回答2:
You need to double-escape the single quote inside the quoted string - so use two single quotes to wrap the string, and four (i.e. two escaped quotes) which will be un-escaped into a pair of single quotes when the query is parsed, and then un-escaped again into the single quote you actually want to insert:
EXEC('UPDATE myTable SET myColumn = ''John''''O Doe''')
回答3:
While OMG Ponies' answer was perfect and helped me as well, something that was not immediately obvious to me is how that worked. Here is how I understood, and may help OP or anyone else still looking, to apply to any situation.
Using a simple example
sp_change_users_login 'update_one', 'LName','Uname'
Transformed
select (' sp_change_users_login ''update_one '', ''LName '' ,''Uname '' ')
All that has been done is, as OMG Ponies said, wrap the entire statement in single quotes(' ). Then, for every single quote that is already present('), place one more to precede it(' ). I am not able to bold the single quotes that were added in the second statement, to make it clearly visible.
回答4:
UPDATE myTABLE SET myCOLUMN='O''John Doe'
EXEC('UPDATE myTABLE SET myCOLUMN=''O''John Doe''')
来源:https://stackoverflow.com/questions/3364232/using-single-quote-in-an-exec-statement-in-sql