Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2005-07-13 : 07:44:52
|
| Pablo writes "SQL 2000 STD SP4, Windows 2000 Server SP4I want to to use parameters to specify the ORDER BY clause using multiple field names. I would like to pass a parameter or multiple parameters to one stored procedure to change the way the data is sorted in a select statement base upon multiple columns in every possible combination of 3 columns.Selectable Sorting Options:Project, ActivityDate, ActivityProject, Activity, ActivityDateActivityDate, Activity, ProjectActivityDate, Project, ActivityActivity, ActivityDate, ProjectActivity, Project Activity, DateThese are just 3 of 6 fields I would like to be able to customize the ORDER BY combinations.I've tried using CASE ...ORDER BY CASE @Sort1WHEN 'Project' THEN ProjectWHEN 'ActivityDate' THEN ActivityDateWHEN 'Activity' THEN ActivityEND,CASE @Sort2WHEN 'Project' THEN ProjectWHEN 'ActivityDate' THEN ActivityDateWHEN 'Activity' THEN ActivityEND,CASE @Sort3WHEN 'Project' THEN ProjectWHEN 'ActivityDate' THEN ActivityDateWHEN 'Activity' THEN ActivityENDBut SQL doesn't allow it becuase items the ORDER BY clause are not unique.I tried using Dynamic sql with the EXEC (sqlstring) + 'ORDER BY ' + @SortOrder without any success. Not sure of syntax.Is there anyway to pass the entire ORDER BY string as a parameter consisting of multiple field names?OrIs there a way to use an IF THEN statement dependent on a parameter to change the ORDER BY using mulitple field names?Or Do I have to create a stored procedure for each ORDER BY combination and then change the sp to use base upon the sort selection?I have searched hi and low and have found many solutions for sorting by 1 column using a parameter but not multiple columns in various orders.Your prompt assistance is appreciated." |
|
|
DonAtWork
Master Smack Fu Yak Hacker
2167 Posts |
Posted - 2005-07-13 : 08:39:30
|
| Perhaps you could sort it in your presentation layer? Otherwise, i would take a shot at Dynamic SQL. You would build your string then exe it, like so : SET @SQL = 'Select <list> from <table> where <condition> ORDER BY ' + @passedinsortorderThen you can EXEC(@SQL)Probably not the best idea, but it would work.*need more coffee*SELECT * FROM Users WHERE CLUE > 0(0 row(s) affected) |
 |
|
|
|
|
|
|
|