SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Avoid dynamic sql in simple situations
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

beyonder422
Posting Yak Master

USA
124 Posts

Posted - 02/03/2006 :  15:57:44  Show Profile  Reply with Quote
I want to avoid dynamic SQL as much as possible, so for example, in a simple dynamic "order by" situation how can I get around this?

SET @strSQL = 'SELECT column1, column2, column3 from table1 order by ' + @order_by

EXEC (@strSQL)

I know I can do an "if" for every column,

If @order_by = 'column1'
SELECT column1, column2, column3 from table1 order by column1
If @order_by = 'column2'
SELECT column1, column2, column3 from table1 order by column2
etc.

but is there a simpler way/trick?


www.beyonder422.com

ackweb
Yak Posting Veteran

54 Posts

Posted - 02/03/2006 :  16:16:54  Show Profile  Reply with Quote
You can use a CASE statement as follows:

SELECT column1, column2, column3 from table1

ORDER BY (CASE WHEN @order_by = 'column1' THEN column1 ELSE (CASE WHEN @order_by = 'column2' THEN column2 ELSE column3 END) END)
Go to Top of Page

beyonder422
Posting Yak Master

USA
124 Posts

Posted - 02/03/2006 :  16:35:58  Show Profile  Reply with Quote
good idea, didn't think about that.


Thanx

www.beyonder422.com
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000