I'm wrining a stored procedure in mysql and I want to use a parameter for the column index in the order-by-clause. I've tried the following:
CREATE PROCEDURE `testProc` (
IN $sortColNum INT
)
BEGIN
SELECT id, title, date, sticky, published, created, updated, content
FROM news
ORDER BY $sortColNum DESC;
END
The stored procedure doesn't throw an error, but the result is unsorted. When i use the column index as a parameter in a prepared statement, it works fine. Why doesn't it work in a stored procedure?
Try this one:
CREATE PROCEDURE `testProc`(IN sortColNum INT)
BEGIN
SET @query = CONCAT ('SELECT id, title, date, sticky, published, created, updated, content
FROM news ORDER BY (',sortColNum,') DESC');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With