Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Tricky order by without writing dynamic T-SQL

Total Hit ( 2474)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


This example shows you how to write dynamic order by statement without writing Dynamic T-SQL which is required to re-compile the execution plan every time you run it.

Click here to copy the following block
if object_id('t1') is not null
   drop table t1

go

CREATE TABLE T1
(
 city VARCHAR(50) ,
 state VARCHAR(50)
)

INSERT T1 VALUES('Atlanta', 'GA')
INSERT T1 VALUES('Chicago', 'IL')
INSERT T1 VALUES('Richmond', 'VA')
INSERT T1 VALUES('Pittusberg', 'PA')
INSERT T1 VALUES('Albany', 'GA')
INSERT T1 VALUES('Huntsville', 'AL')

declare @sortcolumn varchar(50)
declare @sortorder varchar(50)

set @sortcolumn='State'
set @sortorder='DESC'


select
   city,
   State
from t1
order by
   case when @sortcolumn='city' and @sortorder='ASC' then city end asc,
   case when @sortcolumn='city' and @sortorder='DESC' then city end desc,
   case when @sortcolumn='state' and @sortorder='ASC' then state end asc,
   case when @sortcolumn='state' and @sortorder='DESC' then state end desc


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.