NOT LIKE动态sql中的SQL参数

时间:2016-03-30 23:07:33

标签: sql dynamic-sql sql-like

带有NOT LIKE的动态SQL不接受由于某种原因传入的参数。如果我没有将参数传递给动态调用,而是使用其中的单词构建字符串

,它就可以工作

由于某种原因,此调用对于删除的NOT LIKE中的@noteText参数不起作用,并最终删除临时表中的所有内容。 我需要以下内容来处理当带有撇号的单词作为构建时,它会因为无效的字符串引用而错误地抛出错误。

declare @bsearchbody bit=1
declare @bsearchtitle bit =0
declare @notetext varchar(10)='that''s'

create table #matched( id int,note varchar(800),title varchar(800))
INSERT INTO #matched
select 1,'this is just a test. that''s fun.','test1'
UNION ALL
SELECT 2,' note on the ID','the is just a title'
UNION ALL
SELECT 3,'I watched basketball last night','basketball type'

declare @vchsql nvarchar(1000)=N'
DELETE from #matched
WHERE 1=1 AND (' + CASE WHEN @bSearchBody=1 THEN 'ISNULL(note,'''')  NOT LIKE ''%@noteText%''' ELSE '' END +
                    CASE WHEN @bSearchBody=1 AND @bSearchTitle=1 THEN ' AND ' ELSE  '' END +
                    CASE WHEN @bSearchTitle=1 THEN 'ISNULL(title,'''')  NOT LIKE 

    ''%@noteText%''' ELSE '' END + 
                    ')'

                    print @vchsql
    exec sp_executesql @vchsql,N'@notetext varchar(10)',@notetext

当参数@notetext和动态sql看起来像这样时(当单词中没有撇号时),脚本可以工作。

declare @bsearchbody bit=1
declare @bsearchtitle bit =0
declare @notetext varchar(10)='test'

create table #matched( id int,note varchar(800),title varchar(800))
INSERT INTO #matched
select 1,'this is just a test.','test1'
UNION ALL
SELECT 2,' note on the ID','the is just a title'
UNION ALL
SELECT 3,'I watched basketball last night','basketball type'

declare @vchsql nvarchar(1000)=N'
DELETE from #matched
WHERE 1=1 AND (' + CASE WHEN @bSearchBody=1 THEN 'ISNULL(note,'''')  NOT LIKE ''%'+ @noteText+ '%''' ELSE '' END +
                    CASE WHEN @bSearchBody=1 AND @bSearchTitle=1 THEN ' AND ' ELSE  '' END +
                    CASE WHEN @bSearchTitle=1 THEN 'ISNULL(title,'''')  NOT LIKE ''%@noteText%''' ELSE '' END + 
                ')'

                print @vchsql
exec sp_executesql @vchsql,N'@notetext varchar(10)',@notetext

1 个答案:

答案 0 :(得分:1)

问题是SQL将值解释为字符串而不是参数。所以,构建模式。而不是:

'ISNULL(title, '''')  NOT LIKE ''%@noteText%'''

使用:

'COALESCE(title, '''')  NOT LIKE ''%'' + @noteText + ''%'''