これは、MySQL Prepared Statementを使用しています。それらは通常concat()
と一緒に置かれます。また、ユーザー変数には常に@
という記号が使用されます。 DECLAREのローカル変数ではありません。
スキーマ:ストアドプロシージャ
drop table if exists table1;
create table table1
( id int auto_increment primary key,
col2 int not null,
col3 int not null
);
insert table1 (col2,col3) values
(1,1),(41,3),(21,2),(41,1),(31,18),(1141,2);
:
drop procedure if exists sort_by_two;
DELIMITER $$
CREATE PROCEDURE sort_by_two
( IN p_sort_1 VARCHAR(255),
IN p_sort_2 VARCHAR(255)
)
BEGIN
set @theSql=concat("select * from table1 ORDER BY ",p_sort_1,",", p_sort_2);
PREPARE stmt1 from @theSql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END$$
DELIMITER ;
試験:
call sort_by_two('col2','id');
call sort_by_two('col3','col2');
はTESTIように見えますngは正常に動作します。
以下の回答に役立つ作業はありますか? – Drew