views:

890

answers:

1

This is MySQL 5.1.

(Note: I realize there are better ways of doing this particular example, this is not my real code)

Here is what I want to do: The below procedure gets created, but when I CALL it, I get "ERROR 1210 (HY000): Incorrect arguments to EXECUTE"

 DELIMITER //
 CREATE PROCEDURE get_users_by_state(IN state CHAR(2))
 READS SQL DATA
 BEGIN
 SET @mystate = state;
 SET @sql = CONCAT('SELECT * FROM test_table WHERE state = "?"');
 PREPARE stmt FROM @sql;
 EXECUTE stmt USING @mystate;
 END;
 //

 CALL get_users_by_state('AA')//
 ERROR 1210 (HY000): Incorrect arguments to EXECUTE

Is there a way to pass the procedure's parameters to the EXECUTE USING statement? Here is a version that does indeed work, but irks me:

CREATE PROCEDURE get_users_by_state(IN state CHAR(2))
READS SQL DATA
BEGIN
SET @sql = CONCAT('SELECT * FROM test_table WHERE state = "', state, '"')
PREPARE stmt FROM @sql;
EXECUTE stmt;
END;
//

As a side-question, does MySQL have any facilities for escaping strings, like Postgres' quote_literal() and quote_ident()?

For a point of reference, here's something somewhat equivalent for Postgres:

CREATE OR REPLACE FUNCTION get_info_by_state(character)
  RETURNS SETOF ret_type AS
$BODY$
DECLARE
    sql text;
BEGIN
    sql := 'SELECT uid, some_data FROM test_table WHERE state = ' || quote_literal($1);
    RETURN QUERY EXECUTE sql;
END
$BODY$
  LANGUAGE 'plpgsql' VOLATILE

Thanks!

A: 

I don't think you need double quotes around the parameter holder.

Update Here, lest there be no misunderstanding:

DELIMITER //
CREATE PROCEDURE get_users_by_state(IN state CHAR(2))
READS SQL DATA
BEGIN
SET @mystate = state;
SET @sql = CONCAT('SELECT * FROM test_table WHERE state = ?');
PREPARE stmt FROM @sql;
EXECUTE stmt USING @mystate;
END;
//
ChssPly76
If I do this: SET @sql = CONCAT('SELECT * FROM test_table WHERE state = ', state);Then it compiles, but when I CALL it, I get:mysql> CALL get_users_by_state('AA')//ERROR 1054 (42S22): Unknown column 'AA' in 'where clause'So I have to surround it in quotes at some level, it seems
I meant the version with parameter holder, not the concatenation.`SET @sql = 'SELECT * FROM test_table WHERE state = ?';`
ChssPly76
Ah, I see. I would test it, but if I could get that example working, my question would be answered (:
You wanted to run it with EXECUTE USING, no? Am I missing something? I've updated my answer with an actual code sample - it does work for me on 5.1
ChssPly76
sonnofagun - you're right, I thought for sure I had tried that variation
(oh and thanks)