Search code examples
sqlsql-serverstringapostrophe

How to insert a value that contains apostrophe?


My stored procedures:

@type varchar(250) = NULL
AS
Begin
    DECLARE @Sql NVARCHAR(MAX);

    SELECT @Sql = N'SELECT * FROM Match WHERE MatchID Between '
    + CONVERT(NVARCHAR(50),(@currPage - 1)*@recodperpage+1)+ 
            ' and '+ CONVERT(NVARCHAR(50),@currPage*@recodperpage)

    IF @type IS NOT NULL
        SELECT @Sql += N' AND Type = ' + convert(varchar(50),@type)

    EXEC SP_EXECUTESQL @Sql     
END

I EXEC but get error

DECLARE @return_value int

EXEC    @return_value = [dbo].[search_PhanTrang]
        @currPage = 1,
        @recodperpage = 5,
        @Pagesize = 6,
        @type = N'random'

SELECT  'Return Value' = @return_value

Error:

Msg 207, Level 16, State 1, Line 1
Invalid column name 'random'.

How to add ' to my SQL string to fix this error? (' +@type+ ')


Solution

  • Strings need to be placed between single quotes, as you probably already know. Also, if the type contains a quote, you need to double that. That makes for the following line:

    SELECT @Sql += N' AND Type = ''' + REPLACE(convert(varchar(50),@type),'''','''''')+'''';