合并多个SQL Server查询结果

时间:2016-02-19 00:08:35

标签: stored-procedures sql-server-2012 nested-query

以下是两个单独工作的搜索查询。两个查询都会搜索同一个表(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

0 个答案:

没有答案
相关问题