1

This stored procedure accepts a search parameter. I want to join on a table valued function if the search parameter is not null. The way I have written it works, but it seems like lots of duplication of code.

Is there a better way of writing this query to avoid the check for the parameter? Something like a conditional join?

--this is actually passed in to the stored procedure as a parameter which may be NULL (no search text just filters on page) DECLARE @Search varchar(100)

IF @Search IS NULL

WITH Catalog_Search_Results(FIM_NO,Rnk)
AS
(
 SELECT I.FIM_NO, 0
 FROM IMF AS I
) 
SELECT FIM_NO, RNK
 FROM Catalog_Search_Results
 ORDER BY rnk desc

ELSE

WITH Catalog_Search_Results(FIM_NO,Rnk)
AS
(
 SELECT I.FIM_NO,funcItemSearch.RNK
 FROM IMF AS I 
 INNER JOIN dbo.Catalog_ItemSearch(@Search) funcItemSearch ON I.FIM_NO = funcItemSearch.FIM_NO
) 
SELECT FIM_NO, Rnk
 FROM Catalog_Search_Results
 ORDER BY Rnk desc;
asked Mar 4, 2020 at 16:01

1 Answer 1

1

Your code looks ok. Conditional join would lead you to parameter sniffing issue and you used one of two most popular solutions to avoid it. Also you may want to use the second approach - dynamic sql, something like this:

DECLARE @sql NVARCHAR(max);
SET @sql = N'
WITH Catalog_Search_Results(FIM_NO,Rnk)
AS
(
 SELECT I.FIM_NO, 0
 FROM IMF AS I
 '
IF @Search IS NOT NULL
 SET @sql = CONCAT(@sql, 'INNER JOIN dbo.Catalog_ItemSearch(@Search) funcItemSearch ON I.FIM_NO = funcItemSearch.FIM_NO');
SET @sql = CONCAT(@sql, ') 
SELECT FIM_NO, Rnk
 FROM Catalog_Search_Results
 ORDER BY Rnk desc') 
EXEC sp_executesql @sql, N'@Search varchar(100)', @Search 
answered Mar 4, 2020 at 16:28

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.