471,853 Members | 1,038 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,853 software developers and data experts.

"Dynamic" sorting inside a procedure

Hello,
I need to have a stored procedure, which performs sorting. Something like
this:

CREATE PROCEDURE procname
@sortby varchar(30)
AS
BEGIN
SELECT some, columns
FROM some_table
ORDER BY @sortby
END

(of course, i know this won't work, but it gives the idea of what i mean)
Is there a possibility to write a procedure which behaves like that? It is
important for me not to have multiple procedures just for different sorting
criteria...

Thanks,
Mike
Jul 20 '05 #1
3 1685
One method is to build and execute a dynamic SQL statement. For example:

EXEC
(
'SELECT some, columns
FROM some_table
ORDER BY ' + @sortby
)

--
Hope this helps.

Dan Guzman
SQL Server MVP

"Michal Grabowski" <mg******@elka.pw.edu.pl> wrote in message
news:cf**********@julia.coi.pw.edu.pl...
Hello,
I need to have a stored procedure, which performs sorting. Something like
this:

CREATE PROCEDURE procname
@sortby varchar(30)
AS
BEGIN
SELECT some, columns
FROM some_table
ORDER BY @sortby
END

(of course, i know this won't work, but it gives the idea of what i mean)
Is there a possibility to write a procedure which behaves like that? It is
important for me not to have multiple procedures just for different sorting criteria...

Thanks,
Mike

Jul 20 '05 #2
Michal Grabowski (mg******@elka.pw.edu.pl) writes:
CREATE PROCEDURE procname
@sortby varchar(30)
AS
BEGIN
SELECT some, columns
FROM some_table
ORDER BY @sortby
END

(of course, i know this won't work, but it gives the idea of what i
mean) Is there a possibility to write a procedure which behaves like
that? It is important for me not to have multiple procedures just for
different sorting criteria...


http://www.sommarskog.se/dynamic_sql.html gives some suggestions.
--
Erland Sommarskog, SQL Server MVP, es****@sommarskog.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #3
Thanks for all tips!

Regards,
Mike
Jul 20 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Buddy Robbins | last post: by
2 posts views Thread by Randy Yates | last post: by
1 post views Thread by Razzbar | last post: by
2 posts views Thread by Paul E Collins | last post: by
5 posts views Thread by Brad | last post: by
3 posts views Thread by Good Man | last post: by
NeoPa
reply views Thread by NeoPa | last post: by
aboka
reply views Thread by aboka | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.