2

I want best way to call store procedure where i have multiple values in single parameter like City parameter having values like 'london','lyon','kln' and many more.

My stored procedure is like this

CREATE PROCEDURE `GetCityEmpData`(IN `City` VARCHAR(64))
BEGIN 
   SELECT * FROM Employees 
   WHERE Employees.City in (City);
END

and call it like this

call GetCityEmpData("'London',Lyon'") ;

it returns 0 rows where there is data for the given parameters. Is it possible to execute the same without prepare statement?

6
  • here when you pass argument to procedure "'London',Lyon'" its take whole string not commas seprated, thats why its 0 rows. Commented Feb 3, 2016 at 5:59
  • Is there any solution to resolve it? Commented Feb 3, 2016 at 5:59
  • If i remove double quotes then it will take as 2 parameters and throws error. Commented Feb 3, 2016 at 6:00
  • you should remove it in procedure not calling time Commented Feb 3, 2016 at 6:01
  • i haven't given any double quotes in procedure. Could you please suggest example according to my question? Commented Feb 3, 2016 at 6:04

2 Answers 2

6

You could try this :

CREATE PROCEDURE `GetCityEmpData`(`City` VARCHAR(64))
BEGIN
   set @query = concat("SELECT * FROM Employees 
                        WHERE Employees.City in (" , City , ")");

    PREPARE stmt FROM @query;
    EXECUTE stmt ;
END

then you can call your procedure as you wanted :

call GetCityEmpData("'London','Lyon'") ;
Sign up to request clarification or add additional context in comments.

4 Comments

Is this the only way to execute the stored procedure? Please suggest any other solution for this.
Nothing wrong with this. I just want to know is there any alternative?
This solution is working for me, but in a few seconds it is throwing the following error "Lookup Error - MySQL Database Error: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." Any help how to get around this.
This solution is prone to SQL injection use with better care :)
2

You can do this using find_in_set method

CREATE PROCEDURE `GetCityEmpData`(IN `City` VARCHAR(64))
BEGIN 
   SELECT * FROM Employees 
   WHERE FIND_IN_SET (Employees.City ,City);
END

and call it like

call GetCityEmpData('London,Lyon');

2 Comments

This should be the accepted answer. Building SQL dynamically is asking for trouble.
Building SQL dynamically is not that bad if we write parameterized query. But after writing it using concat method I find my hands dirty :)

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.