3

I trying to write a stored procedure where I would like to test a passed in argument for certain value through an IF/Else statement and ultimately INTERSECT the result with another table. Something like the following as a non-working pseudo example.

ALTER PROCEDURE [dbo].[Search]
    @Keyword nvarchar(MAX),
    @ClasificationId int
AS
BEGIN
    SET NOCOUNT ON;

    IF (@Keyword != null)
        SELECT * FROM Table WHERE [Keyword] LIKE @Keyword
    ELSE 
        SELECT * FROM Table 

    INTERSECT

    IF (@Classification != null)
        SELECT * FROM Table WHERE [ClassificationID] = @ClassificationId
    ELSE 
        SELECT * FROM Table 
END
2
  • ClassificationID is a NVARCHAR(MAX)? Unlike most <ID> fields no? Commented May 29, 2013 at 19:47
  • loool you're right. Good point Commented May 30, 2013 at 10:13

2 Answers 2

4

You can meet your requirement with a simple modification to each WHERE clause.

SELECT 
   * 
FROM 
   Table 
WHERE 
   @keyword IS NULL 
OR [Keyword] LIKE @Keyword
INTERSECT
SELECT 
  * 
FROM 
  Table 
WHERE 
  @ClassificationId IS NULL 
OR [ClassificationID] = @ClassificationId
Sign up to request clarification or add additional context in comments.

Comments

3

this is easier done as a catch all type query - I recommend the dynamic sql approach as done properly: you'll get a good plan for each permutation of query.

Read this: http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

1 Comment

Interesting article. Thanks

Your Answer

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.