如何插入包含撇号的值?

How to insert a value that contains apostrophe?

我的存储过程:

@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

我执行但出现错误

DECLARE @return_value int

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

SELECT  'Return Value' = @return_value

错误:

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

如何将 ' 添加到我的 SQL 字符串中以修复此错误? (' +@type+ ')

您可能已经知道,字符串需要放在单引号之间。此外,如果类型包含引号,则需要将其加倍。这使得以下行:

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