2

I am trying to run the dynamic query using a stored procedure in which I am sending the where condition case for example.

My sample stored procedure is shown here:

CREATE PROCEDURE `Storedproc`(IN getwhereconditon varchar(1000))
    BEGIN
    set @param=getwhereconditon ;
    SET @S=concat('Select * from table where (1)',@param);
    PREPARE stmt1 FROM @s;
    EXECUTE stmt1;
    END

Here my stored procedure's name is Storedproc in which I am passing the where condition details and when I call my stored procedure I am getting this error

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '0tablecol=1' at line

8
  • Show the real value you are passing.And what`s with the (1)? Commented Jun 28, 2014 at 10:27
  • @Mihai where(1) is the condition if none of the value of comes it will run without an error Storeproc(and nqh.nqh_quarry_id=2) Commented Jun 28, 2014 at 10:36
  • why are you using and in Storeproc(and nqh.nqh_quarry_id=2) Commented Jun 28, 2014 at 10:39
  • The error message doesnt seem to be for the parameter above.Also you shoud have quotes for your parameter. Commented Jun 28, 2014 at 10:49
  • there is problem in my SP which i Can't able to identify it and yes i am send the parameter in a quotes.If you got any better solution in my In case of my SP then help me out Commented Jun 28, 2014 at 10:53

1 Answer 1

3

Try

DELIMITER //
CREATE PROCEDURE myproc(IN _where VARCHAR(512))
BEGIN
  SET @sql = 'SELECT * FROM table1';
  IF COALESCE(_where, '') <> '' THEN
    SET @sql = CONCAT(@sql, ' WHERE ', _where);
  END IF;
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END //
DELIMITER ;

or

DELIMITER //
CREATE PROCEDURE myproc(IN _where VARCHAR(512))
BEGIN
  SET @sql = CONCAT('SELECT * FROM table1', COALESCE(CONCAT(' WHERE ', NULLIF(_where, '')), ''));
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END //
DELIMITER ;

Sample usage:

CALL myproc(NULL);
CALL myproc('name=''John''');
CALL myproc('age > 25');
CALL myproc('age < 28 OR age > 30');

Here is SQLFiddle demo

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

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.