MySQL Forums
Forum List  »  Stored Procedures

Re: Stored Procedure with a "ORDER BY" parameter
Posted by: Roland Bouman
Date: November 09, 2005 02:49AM

Hi!

It doesn't work like that. Variables in the SELECT statement are just expressions, so, assuming the the value of sOrder is 'u_FirstName, u_LastName ASC', youre statement evaluates to just that:

SELECT u_ID
, u_AccountName
, u_FirstName
, u_LastName
, u_Email
, u_Administrator
, u_Disabled
FROM Users
ORDER BY 'u_FirstName, u_LastName ASC';

There are two ways to achieve what you want. You could either build the SELECT statement string dynamically in the .NET code, and excecute that:

comm.CommandText = "SELECT...ORDER BY " + orderBYList

etc.

This is by far the easiest method. (You could of course write a .NET function that builds the statement to encourage reuse in your code)
However, if you want to be able to reuse this dynamic order by list across different applications and language, you'r really want to put into a procedure, and do it there.

You can do that through the prepared statement syntax:

DELIMITER $$
DROP PROCEDURE IF EXISTS `MyWebSite`.`UsersList` $$
CREATE PROCEDURE `UsersList`( IN sorder varchar(250) )
BEGIN
set @stmt_text := concat(
"SELECT u_ID"
, ", u_AccountName"
, ", u_FirstName"
, ", u_LastName"
, ", u_Email"
, ", u_Administrator"
, ", u_Disabled "
, "FROM Users "
, "ORDER BY ?"
);
PREPARE stmt_handle FROM @stmt_text;
set @sOrder := sOrder;
EXECUTE stmt_handle USING @sOrder;
DEALLOCATE PREPARE stmt_handle;
END $$
DELIMITER ;

see: http://dev.mysql.com/doc/refman/5.0/en/sqlps.html
and http://mysql.gilfster.com/page.php?parent_id=1.3&page_id=1.3.6

Options: ReplyQuote


Subject
Views
Written By
Posted
Re: Stored Procedure with a "ORDER BY" parameter
3228
November 09, 2005 02:49AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.