Escape Character in SQL Server

前端 未结 9 1404
时光取名叫无心
时光取名叫无心 2020-11-29 03:22

I want to use quotation with escape character. How can I do?

I have received error in SQL Server

Unclosed quotation mark after the character strin

相关标签:
9条回答
  • 2020-11-29 03:37

    You can escape quotation like this:

    select 'it''s escaped'
    

    result will be

    it's escaped
    
    0 讨论(0)
  • 2020-11-29 03:38

    You can define your escape character, but you can only use it with a LIKE clause.

    Example:

    SELECT columns FROM table
    WHERE column LIKE '%\%%' ESCAPE '\'
    

    Here it will search for % in whole string and this is how one can use ESCAPE identifier in SQL Server.

    0 讨论(0)
  • 2020-11-29 03:39

    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'
    
    0 讨论(0)
  • 2020-11-29 03:42

    To keep the code easy to read, you can use square brackets [] to quote the string containing ' or vice versa .

    0 讨论(0)
  • 2020-11-29 03:44

    Escaping quotes in MSSQL is done by a double quote, so a '' or a "" will produce one escaped ' and ", respectively.

    0 讨论(0)
  • 2020-11-29 03:45

    If you want to escape user input in a variable you can do like below within SQL

      Set @userinput = replace(@userinput,'''','''''')
    

    The @userinput will be now escaped with an extra single quote for every occurance of a quote

    0 讨论(0)
提交回复
热议问题