Discussion Locked

Parameter in SQLServer Stored Procedure

0 helpful
3 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
Is there a way to pass a parameter to a MS SQL Server Stored Procedure that will tell the ORDER BY clause which field to sort by?

3 replies

by agibbs

I spent a few hours up late several weeks ago trying to figure out the same thing . . . :-)

It only works if you pass the column NUMBER as a value, not the column name . . . so, it's important that you don't re-order your columns after writing the stored procedure.

CREATE PROCEDURE sp_SELECT_ORDER_BY (
@orderby as int)
AS
BEGIN
/*********************************
* the @orderby parameter should be the column
* that you want the SELECT statement to
* be ordered by. Example:
* if the third column is customer_name, and
* you want the SELECT ordered by
* customer_name, use:
* EXEC sp_SELECT_ORDER_BY 3
*********************************/

SELECT * FROM my_table
ORDER BY @orderby

END

This discussion is closed to new replies.