1

I have a simple select and two parameters.

@first
@second

SELECT ProductID, ProductName, ProductType, ProductLevel
FROM ProductTable

When I execute the procedure if both parameters have no values then I need this part to be executed:

WHERE ProductType = 1 AND ProductLevel = 1

IF I have value of first parameter then :

WHERE ProductType = 2 AND ProductName LIKE  @first + '%'

IF I have value of second parameter then :

WHERE ProductType =3 AND ProductName LIKE  @second + '%'

Can someone help me to implement this logic and create valid stored procedure ?

3 Answers 3

4

If I understand you right then you need the next 'WHERE' statement:

WHERE 
    (@first IS NULL AND @second IS NULL AND ProductType = 1 AND ProductLevel = 1)
    OR
    (@first is NOT NULL AND ProductType = 2 AND ProductName LIKE @first + '%')
    OR
    (@second is NOT NULL AND ProductType = 3 AND ProductName LIKE @second + '%')
Sign up to request clarification or add additional context in comments.

2 Comments

When I declare parameter and execute procedure it still expects parameter who are not supplied if I do not write any values to them :/
What if you make your parameter as optional? @first VARCHAR(5) = NULL
1

You Should try IN Format:

DROP PROCEDURE IF EXISTS products;

DELIMITER $$

CREATE PROCEDURE products(
IN p_ProductName,
IN p_ProductType,
IN p_ProductLevel
)

BEGIN

   SELECT * FROM ProductTable WHERE ProductName LIKE '%p_ProductName%', ProductType LIKE '%p_ProductType%' , ProductLevel LIKE '%p_ProductLevel%';

END$$

Comments

1

Adding Another way,

declare @whereCondition varchar(100)

if(@first='' && @second='')
 @whereCondition=ProductType = 1 AND ProductLevel = 1
else if(@first<>'' && @second='')
 @whereCondition=ProductType = 2 AND ProductName LIKE  @first + '%'
else if(@first='' && @second<>'')
 @whereCondition=ProductType =3 AND ProductName LIKE  @second + '%'

exec('SELECT ProductID, ProductName, ProductType, ProductLevel
FROM ProductTable where=@whereCondition')

if the logic seems bigger, we can achieve by this way.

Comments

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.