0

以下は、別々に機能する 2 つの検索クエリです。どちらのクエリも同じテーブル ( KnowledgeBaseArticles) を検索し、パラメーター@SearchWithWildcardおよびを使用して検索文字列を取得します@SearchParam

これらのクエリをストアド プロシージャ (おそらく 2 つ) に結合して、重複のない 1 つの結合された結果セットを返したいと考えています。最初のクエリの一時テーブルを作成し、結果を 2 番目にネストしようとしました。最初のクエリをストアド プロシージャに適用し、2 番目のクエリを実行して結果を結合しようとしましたが、構文が間違っていて機能しません。 .

これを 1 つのクエリに組み込むための最良のアプローチを誰かが提案できる場合は、その支援をいただければ幸いです。

最初の検索クエリ:

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

2 番目の検索クエリ:

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