0

I have created one Store procedure in mysql it accept 2 parameter but parameter can be null so based on that parameter value i wanted to generate dynamic where condition

DELIMITER$$
CREATE PROCEDURE GetValue(IN PID INT,IN PName VARCHAR(255))
 BEGIN
 SELECT * 
 FROM tblTEMP
 WHERE ID= PID AND NAME=;  
 END$$
DELIMITER ;

but in above Store procedure problem is PID or PName either one or both may Null in that case what should i write in where condition? i tried like this

DELIMITER$$
    CREATE PROCEDURE GetValue(IN PID INT,IN PName VARCHAR(255))
     BEGIN
        DECLARE WhereCondition VARCHAR(300);
         IF NULLIF(PID, '') IS NULL AND NULLIF(PName , '') IS NULL
             WhereCondition = "1=1";
         IF NULLIF(PID, '') IS NULL
             WhereCondition = "NAME=PName";  
         IF NULLIF(PName, '') IS NULL
             WhereCondition = "ID=PID";
     SELECT * 
     FROM tblTEMP
     WHERE  WhereCondition ;  
     END$$
    DELIMITER ;

1 Answer 1

3
 DELIMITER $$
    CREATE PROCEDURE GetValue(IN PID INT,IN PName VARCHAR(255))
     BEGIN
        DECLARE WhereCondition VARCHAR(300);

        IF NULLIF(PID, '') IS NULL AND NULLIF(PName , '') IS NULL THEN
           SET WhereCondition = '1=1';
        ELSEIF NULLIF(PID, '') IS NULL THEN
           SET WhereCondition = 'NAME=PName';  
        ELSEIF NULLIF(PName, '') IS NULL THEN
           SET WhereCondition = 'ID=PID';
        END IF;

         SET @query =CONCAT("SELECT * FROM tblTEMP ",WhereCondition);
         PREPARE stmt FROM @query;
         EXECUTE stmt;
     END$$
 DELIMITER ;

Just try above code.I had mention dynamic query using PREPARE statement and Execute it with Execute command.Hope this will help.

Sign up to request clarification or add additional context in comments.

2 Comments

it shows an error like "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WhereCondition = "1=1"; IF NULLIF(PID, '') IS NULL WhereCo' at line 12"
same error "Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WhereCondition = "1=1"; ELSEIF NULLIF(PID, '') IS NULL Whe' at line 12"

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.