SQL Escape ' '

前端 未结 7 1150
星月不相逢
星月不相逢 2021-01-12 22:49

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)


        
相关标签:
7条回答
  • 2021-01-12 23:17

    A double single ('') quote will act like a single single quote when inside a string literal.

    Have you tried using a variable?

    declare @karl_name varchar(10);
    set @karl_name = '''Karl''';
    
    SELECT * FROM Table WHERE [Name] = @karl_name
    
    0 讨论(0)
  • 2021-01-12 23:18

    Simply escape the apostrophes by using the escaping bar \ like this 'SELECT * FROM Table WHERE [Name] = ' \'Karl\' ' '

    Hope it helps

    0 讨论(0)
  • 2021-01-12 23:27

    This works on my machine from SQL Server Management Studio:

    @query varchar(max)
    
    SET @query = 'SELECT * FROM Table WHERE [Name] = ''''''Karl'''''''
    
    EXEC(@query)
    
    0 讨论(0)
  • 2021-01-12 23:27

    This works:

    create table #demo([Name] varchar(max))
    insert into #demo([Name]) values('''Karl''')
    insert into #demo([Name]) values('Karl')
    declare @query varchar(max)
    set @query = 'SELECT * FROM #demo WHERE [Name] = ''''''Karl'''''''
    EXEC(@query)
    

    Output:

    'Karl'
    

    But if 'Karl' is variable text, it's highly recommended to use something like this instead:

    declare @query nvarchar(max)
    declare @param varchar(max)
    set @param = N'''Karl'''
    set @query = N'SELECT * FROM #demo WHERE [Name] = @param'
    exec sp_executesql @query, N'@param varchar(max)', @param
    
    0 讨论(0)
  • 2021-01-12 23:28

    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
    
    0 讨论(0)
  • 2021-01-12 23:34

    do like this SET @query = 'SELECT * FROM Table WHERE [Name] = ''''Karl'''''

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