非常难看cludge恐怕像MySQL存储过程目前不支持数组类型PARAMS:
调用示例:
mysql> call foo('2,4,6');
+---------+----------+
| user_id | username |
+---------+----------+
| 2 | b |
| 4 | d |
| 6 | f |
+---------+----------+
3 rows in set (0.00 sec)
完整的脚本:
drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varchar(32) unique not null
)
engine=innodb;
insert into users (username) values ('a'),('b'),('c'),('d'),('e'),('f'),('g');
drop procedure if exists foo;
delimiter #
create procedure foo
(
in p_id_csv varchar(1024)
)
proc_main:begin
declare v_id varchar(10);
declare v_done tinyint unsigned default 0;
declare v_idx int unsigned default 1;
if p_id_csv is null or length(p_id_csv) <= 0 then
leave proc_main;
end if;
-- split the string into tokens and put into an in-memory table...
create temporary table ids(id int unsigned not null)engine = memory;
while not v_done do
set v_id = trim(substring(p_id_csv, v_idx,
if(locate(',', p_id_csv, v_idx) > 0,
locate(',', p_id_csv, v_idx) - v_idx, length(p_id_csv))));
if length(v_id) > 0 then
set v_idx = v_idx + length(v_id) + 1;
insert into ids values(v_id);
else
set v_done = 1;
end if;
end while;
select u.* from users u
inner join ids on ids.id = u.user_id
order by u.username;
drop temporary table if exists ids;
end proc_main #
delimiter ;
call foo('2,4,6');
这是制作中的SQL注入漏洞。 – 2012-01-27 00:52:23
事件如果存在SQL注入的可能性,尝试在存储过程中进行防御性编程(或与数据库或其数据无关的事情)可能会导致无法维护的混乱。我说这取决于程序员是否可以传递有效参数或避免存储过程。 – 2012-01-30 23:34:58
问题不在于存储过程。它正在评估部分由用户输入生成的代码。这在* any语言中是一个糟糕的主意,而不仅仅是SQL。正如上面的f00所展示的那样,这个问题可以通过使用SQL来解决,而不会像引导代码那样引入漏洞。 – 2012-01-30 23:50:07