Home > Archive > MS SQL Server > December 2006 > Does Sql 2005 allow ORDER BY @Variable ?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Does Sql 2005 allow ORDER BY @Variable ?
Dan E

2006-12-05, 7:12 pm

I am writing a stored proc and do not want to use dynamic sql. Does Sql
2005 allow ORDER BY @Variable? The query compiler accepts it, but it
doesn't work. My @Variable is a VARCHAR(50).

Thanks!


Arnie Rowland

2006-12-05, 7:12 pm

Not directly. You could use a CASE structure to allow alternative orderings. Here is one idea:

USE Northwind
GO

DECLARE @OrderVar varchar(20)
SET @OrderVar = 'LastName'

SELECT
LastName,
FirstName
FROM Employees
ORDER BY CASE @OrderVar
WHEN 'LastName' THEN LastName
WHEN 'FirstName' THEN FirstName
END ASC,
CASE @OrderVar
WHEN 'LastName' THEN FirstName
WHEN 'FirstName' THEN LastName
END ASC

--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc

Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous

You can't help someone get up a hill without getting a little closer to the top yourself.
- H. Norman Schwarzkopf


"Dan E" <dan_english2@cox.net> wrote in message news:u1AfegKGHHA.1280@TK2MSFTNGP04.phx.gbl...
>I am writing a stored proc and do not want to use dynamic sql. Does Sql
> 2005 allow ORDER BY @Variable? The query compiler accepts it, but it
> doesn't work. My @Variable is a VARCHAR(50).
>
> Thanks!
>
>

Aaron Bertrand [SQL Server MVP]

2006-12-05, 7:12 pm

http://databases.aspfaq.com/databas...-by-clause.html




"Dan E" <dan_english2@cox.net> wrote in message
news:u1AfegKGHHA.1280@TK2MSFTNGP04.phx.gbl...
>I am writing a stored proc and do not want to use dynamic sql. Does Sql
>2005 allow ORDER BY @Variable? The query compiler accepts it, but it
>doesn't work. My @Variable is a VARCHAR(50).
>
> Thanks!
>
>



Sponsored Links





Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive | Programming forum archive

Copyright 2009 droptable.com