0

下面是两个单独工作的搜索查询。两个查询都搜索同一个表 ( KnowledgeBaseArticles) 并接收带有参数的搜索字符串@SearchWithWildcard@SearchParam

我想将这些查询组合成一个存储过程(可能是两个),该过程将返回一个组合结果集而没有任何重复。我尝试创建第一个查询的临时表并将结果嵌套在第二个查询中,并将第一个查询应用于存储过程并尝试在第二个查询中执行和连接结果,但语法错误并且不起作用.

如果有人可以建议开始将其构建到一个查询中的最佳方法,我将非常感谢您的帮助。

第一个搜索查询:

declare @i1 int;
declare @i2 int;
declare @Word varchar(100);
declare @Words table (Word varchar(100) not null);
declare @WordCount as integer;
declare @SearchWithWildcard nvarchar(1000)
declare @MatchType int = 0

set nocount on

-- Parse the @SearchWithWildcard to extract all words:
if (@MatchType != 2)
begin
  set @SearchWithWildcard = ' ' + @SearchWithWildcard + ' ';
  set @i1 = 1;

  while (@i1 != 0)
  begin
    set @i2=charindex(' ', @SearchWithWildcard, @i1+1)

    if (@i2 != 0)
    begin
      set @Word = rtrim(ltrim(substring(@SearchWithWildcard, @i1+1, @i2-@i1)))
      if @Word != '' insert into @Words select @Word
      end
    set @i1 = @i2
    end
  end
else
  insert into @Words select ltrim(rtrim(@SearchWithWildcard))
-- Get the total # of words:

set @WordCount = (select count(*) from @Words)

-- Return Results in order of relevance:
select a.MatchPct, T.*
from KnowledgeBaseArticles T
inner join  (select ID, Count(*)  * 1.0 / @WordCount as MatchPct from KnowledgeBaseArticles T
inner join @Words W on ' ' + T.KeyWords + ' ' like '%[^a-z]' + Word + '[^a-z]%'
group by ID) a on T.ID = a.ID
where MatchPct = 1 or @MatchType <>1 
order by MatchPct

第二个搜索查询:

Declare @SearchWithWildcard NVARCHAR(1000)
Declare @SearchParam nvarchar(1000)
Declare @CatID integer
set @CatID = 0

BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

IF @SearchParam != ''
    SET @SearchWithWildcard = @SearchParam
ELSE
    SET @SearchWithWildcard = ''

IF @CatID = 0 AND NULLIF(@SearchParam, '') IS NULL
   SELECT * 
   FROM KnowledgeBaseArticles 
   WHERE Deleted = 0

ELSE IF @CatID = 0 AND NULLIF(@SearchParam, '') IS NOT NULL
   SELECT * 
   FROM KnowledgeBaseArticles
   WHERE (ArticleTextOnly like '% ' + @SearchWithWildcard + ' %' OR Title like '% ' + @SearchWithWildcard + ' %') and Deleted = 0

ELSE IF @CatID > 0 AND NULLIF(@SearchParam, '') IS NOT NULL
   SELECT * 
   FROM KnowledgeBaseArticles
   WHERE CategoryID = @CatID AND (ArticleTextOnly like '% ' + @SearchWithWildcard + ' %' OR Title like '% ' + @SearchWithWildcard + ' %') and Deleted = 0

ELSE IF @CatID > 0 AND NULLIF(@SearchParam, '') IS NULL
   SELECT * 
   FROM KnowledgeBaseArticles
   WHERE CategoryID = @CatID and Deleted = 0
END
4

0 回答 0