如何将多个关键字传递给存储过程

时间:2013-01-26 23:10:08

标签: sql sql-server-2008

我有这个存储过程,它返回包含指定关键字的记录。

CREATE procedure [dbo].[SearchKeywordPaged](
    @KeyWordFilter varchar(50)
    ,@PageNumber int = 1)      

as
begin

declare @PageSize int = 50
declare @FirstRow int
declare @LastRow int
declare @TotalRows int

SELECT      @FirstRow = (@PageNumber - 1) * @PageSize + 1,
            @LastRow = (@PageNumber - 1) * @PageSize + @PageSize;

select @TotalRows =      COUNT(*) from 
    [Quotes] q inner join [Keywords] k 
    ON q.id = k.Quoteid where k.Keyword = @KeyWordFilter;

with Results as
(                  
    SELECT            
        q.*
        ,ROW_NUMBER() over (Order By Author asc) as Instance_Count
        ,@TotalRows as the_Count
    FROM [Quotes] q
    INNER JOIN [Keywords] k ON q.id = k.Quoteid
    WHERE k.Keyword = @KeyWordFilter
)            

select      *
from      results
where      Instance_Count between @FirstRow and @LastRow
order by Instance_Count asc

end

如何修改此存储过程以接受多于1个搜索关键字?

2 个答案:

答案 0 :(得分:1)

创建一个将字符串转换为表格的函数。您可以使用以下示例:

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fn_SplitString]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fn_SplitString]
GO
CREATE   FUNCTION [dbo].[fn_SplitString]    (@xStr varchar(8000))
RETURNS @out table (
    x varchar(500))  AS  
begin

declare @lp int set @lp=1
declare @xlen int
set @xlen=len(@xstr)

declare @xchar char(1)
declare @thisSplit varchar(50)
set @thisSplit=''

while @lp <= @xlen
 begin
    set @xchar=substring(@xstr,@lp,1)

    set @thisSplit=@thisSplit + @xchar

        if (@xchar=',') or (@lp=@xlen)
         begin
            insert into @out (x) values (replace(@thisSplit,',',''))
            set @thisSplit=''
         end
    set @lp=@lp+1   
 end


RETURN  
end
GO
select X from fn_SplitString('aaa,bbb,cccc')

然后,修改存储过程的WHERE子句,如下所示:

WHERE k.Keyword in (select x from fn_SplitString(@KeyWordFilter) ) 

最后,您可以使用SP将关键字列表作为逗号分隔列表传递,如下所示:

exec [SearchKeywordPaged]  @KeyWordFilter='keyword1,keyword2,...'

答案 1 :(得分:0)

您可能必须在存储过程中执行一些动态操作。例如:

declare @keywords varchar(50);
declare @sql  varchar(256);

-- @keywords is defined locally here, but it would be passed into your proc.
-- these are all single quotes.
select @keywords = ' ''keyword1'', ''keyword2'', ''keyword3'' '

select @sql = 'select * from a_table where keyword in (' + @keywords + ')'
exec(@sql)