-1

I´m trying to define a stored procedures which accepts 2 parameteres , one would be the table column which has to be equal with the second parameter i will provide. Code :

 DELIMITER $$

    CREATE DEFINER=`root`@`localhost` PROCEDURE `selectUserByField`(IN _field varchar(150) , IN _value varchar(150))
    BEGIN
  SET @sql = CONCAT('SELECT * FROM Users WHERE', _field, '=' ,_value);
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
    END

The thing is that i don´t know how to provide the _value param as a string. If i run it like this i get a Mysql 1064 near ´=myEmail´( params where ´userEmail´,´myEmail´). Thanks !

alexsc
  • 1,196
  • 1
  • 11
  • 21

1 Answers1

0

In your below code, you are missing a space after WHERE. It should be like below; give a space after WHERE and in =

SET @sql = CONCAT('SELECT * FROM Users WHERE ', _field, ' = ' ,_value);
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • Are you certain that, you used the exact code posted in answer; cause now the query will be formed like `SELECT * FROM Users WHERE userEmail = myEmail` which should work just fine; whereas in your posted code the query was getting formed as `SELECT * FROM Users WHEREuserEmail = myEmail` and so you were getting 1064 syntax error. If there is something other than what you have posted in question then that's a blackbox for me. – Rahul Aug 01 '14 at 00:23
  • CONCAT('SELECT * FROM Users WHERE ', _field, ' = ' ,_value); – alexsc Aug 01 '14 at 06:13
  • i managed to get it to work for numeric values like ID, but when i access it with string it doesn´t return anything – alexsc Aug 01 '14 at 06:16
  • Do you know any method to tell mysql that 'myEmail' is a string ? – alexsc Aug 01 '14 at 06:20
  • My final query that works fine for everything is : SET @sql = CONCAT('SELECT * FROM Users WHERE ', _field, ' = ' , '"', _value, '"'); PREPARE stmt FROM @sql; – alexsc Aug 01 '14 at 06:28