I’d like to be able to use a parameter variable in the order by clause of a cursor declaration. I’m using MySQL 5.5.21. Here’s the code I tried to use. There are no errors, but the output is not sorted by the column I provide in the parameter.
CREATE PROCEDURE getData(IN start_id INT, IN end_id INT, IN col_sort VARCHAR(16), IN max_date DATE)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE id_num INT;
DECLARE rid_num LONG;
DECLARE cur1 CURSOR FOR SELECT `ID`,`rid` FROM `clients` WHERE `rid` > 0 AND `date_live` < max_date ORDER BY col_sort LIMIT start_id, end_id;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
(etc.)
I’m curious to see if this can be done. I’d like not to have to define multiple stored procedures for each possible column. Thanks in advance.
The output is sorted by the input that you provide, i.e. the string value, which is effectively not sorting at all as all rows get the same value.
You would need a
caseto sort by different columns:This of course needs all the columns to be of the same data type. If you have different data types, then you need one
casefor each data type.Another alternative would be to create the SQL by concatenating strings, and then execute that.