TSQL: query with optional join

I have a ui search with 3 all optional search criteria. 2 of them are simple criteria for the where statement, which I would have to solve with this: Stored procedure with optional "WHERE" Parameters .

The final criterion is the use of full-text search, in which I join the result from the ContainsTable. Is there any trick I can use to put everything in one stored procedure? Or should I make two queries: one with full text search and one without?

Edited: I would also put my request here, sorry, this

select Table1.* from Table1
join
(
 select [Key], SUM(Rank) as Rank from
 (
  SELECT [Key], Rank*3 as Rank FROM Table1ShortSearch(@Keywords) union all
  SELECT [Key], Rank*2 as Rank FROM Table1LongSearch(@Keywords)
 ) as RankingTbl
 group by [Key]
) as r
on Table1.Id = r.[Key]

where ( @Status_Id Is Null Or Status_Id = @Status_Id )

order by r.Rank Desc

Thank.

+3
2

:

EXISTS :

Select ..
From ..
Where ( @Status_Id Is Null Or Status_Id = @Status_Id )
 And (@Date Is Null Or [Date] = @Date )
 And (@Criteria Is Null Or Exists(
         Select 1
         From ContainsTable(TableName, Column1,...,ColumnN, @Criteria..) As SearchTable1
         Where SearchTable1.PK = OuterTable.PK
         ) )

:

, . 1 , @Keywords . SELECT freetext. , @Keywords null?

freetext , , @Keywords - , - :

Select ...
From Table1
Where ( @Status_Id Is Null Or Status_Id = @Status_Id )
    And ...
    And (
        @Keywords Is Null
        Or Exists   (
                    Select 1
                    From Table1ShortSearch(@Keywords) As T1
                    Where T1.Key = Table1.Key
                    )
        Or Exists   (           
                    Select 1
                    From Table1LongSearch(@Keywords) As T2
                    Where T2.Key = Table1.Key
                    )
        )

freetext, , , CTE , Left Join , , @Keywords . :

Select ...
From Table1
    Left Join   (
                 Select [Key], Sum(Rank) as Rank 
                 From   (
                        Select [Key], Rank*3 As Rank 
                        From Table1ShortSearch(@Keywords) 
                        Union All 
                        Select [Key], Rank*2 As Rank 
                        From Table1LongSearch(@Keywords)
                        ) As RankingTbl
                Group By [Key]
                ) as R
        On R.[Key] = Table1.Id
Where ( @Status_Id Is Null Or Status_Id = @Status_Id )
    And ...
    And ( @Keywords Is Null Or R.Key Is Not Null )
Order By R.Rank Desc
+2

Source: https://habr.com/ru/post/1734436/


All Articles