Search code examples
sql-serverescapingchar

Escape Character in SQL Server


I want to use quotation with escape character. How can I do to avoid the following error when one has a special character?

Unclosed quotation mark after the character string.


Solution

  • To escape ' you simly need to put another before: ''

    As the second answer shows it's possible to escape single quote like this:

    select 'it''s escaped'
    

    result will be

    it's escaped
    

    If you're concatenating SQL into a VARCHAR to execute (i.e. dynamic SQL), then I'd recommend parameterising the SQL. This has the benefit of helping guard against SQL injection plus means you don't have to worry about escaping quotes like this (which you do by doubling up the quotes).

    e.g. instead of doing

    DECLARE @SQL NVARCHAR(1000)
    SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
    EXECUTE(@SQL)
    

    try this:

    DECLARE @SQL NVARCHAR(1000)
    SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = @Field1'
    EXECUTE sp_executesql @SQL, N'@Field1 VARCHAR(10)', 'AAA'