SQL Escape ' '

前端 未结 7 1152
星月不相逢
星月不相逢 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: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
    

提交回复
热议问题