我想将整数数组作为参数传递给存储过程,怎么做呢?
CREATE PROCEDURE rd22(unitList INT)
BEGIN
SELECT * FROM abet INNER JOIN a ON a.id = abet.alarm_source
AND a.unit IN (unitList)
WHERE abet.begin_timestamp = 1395874800000;
END
这就是存储过程的样子,我希望得到这样的东西:
SET @val = [1,2,3];
CALL rd22(@val);
我能想到的一种方法是传递一个字符串,然后以某种方式将其转换为整数。有没有其他微妙的方法来实现这个目标。
感谢您的时间。
干杯。
答案 0 :(得分:1)
你不能这样做,当你在查询中以逗号分隔的字符串传递param时它只会在执行in clause
时获取第一个值,你需要使用带有预准备语句的动态查询
CREATE PROCEDURE rd22(unitList varchar(100))
BEGIN
set @ul = unitList;
set @qry = concat("select * from abet INNER JOIN a ON a.id = abet.alarm_source and a.unit IN(",@ul,") WHERE abet.begin_timestamp = 1395874800000");
prepare stmt from @qry;
execute stmt;
END
电话会议
SET @val = '1,2,3';
CALL rd22(@val);
以下是mysql中的测试用例
mysql> select * from test ;
+------+---------------------+---------------------+----------+
| id | created | resolved | status |
+------+---------------------+---------------------+----------+
| 1 | 2015-05-10 00:00:00 | 1970-01-01 00:00:00 | open |
| 2 | 2015-05-10 00:00:00 | 1970-01-01 00:00:00 | new |
| 3 | 2015-05-10 00:00:00 | 2015-05-12 00:00:00 | resolved |
| 4 | 2015-05-11 00:00:00 | 1970-01-01 00:00:00 | open |
| 5 | 2015-05-11 00:00:00 | 1970-01-01 00:00:00 | new |
| 6 | 2015-05-11 00:00:00 | 2015-05-11 00:00:00 | resolved |
| 7 | 2015-05-12 00:00:00 | 1970-01-01 00:00:00 | open |
| 8 | 2015-05-12 00:00:00 | 1970-01-01 00:00:00 | new |
| 9 | 2015-05-12 00:00:00 | 1970-01-01 00:00:00 | open |
+------+---------------------+---------------------+----------+
9 rows in set (0.00 sec)
mysql> delimiter //
mysql> CREATE PROCEDURE testin(vals varchar(100))
-> BEGIN
-> set @ul = vals;
-> set @qry = concat("select * from test where id IN(",@ul,")");
-> prepare stmt from @qry;
-> execute stmt;
-> END;//
Query OK, 0 rows affected (0.03 sec)
mysql> set @val = '3,4,6';
Query OK, 0 rows affected (0.00 sec)
mysql> call testin(@val);
+------+---------------------+---------------------+----------+
| id | created | resolved | status |
+------+---------------------+---------------------+----------+
| 3 | 2015-05-10 00:00:00 | 2015-05-12 00:00:00 | resolved |
| 4 | 2015-05-11 00:00:00 | 1970-01-01 00:00:00 | open |
| 6 | 2015-05-11 00:00:00 | 2015-05-11 00:00:00 | resolved |
+------+---------------------+---------------------+----------+
3 rows in set (0.01 sec)