Friday, March 30, 2012

Order by, Using a param

How do you allow sorting via one of the params?
I would like to do something like...
declare @.c char(50)
,@.s char(30)
set @.c = 'SomeClient'
set @.s = 'SomeColumn'
select @.s
select *
from MyTable
where rtrim(clientName) = rtrim(@.c)
order by rtrim(@.s)
thanks in advance..
bob.John 3:16 wrote:
> How do you allow sorting via one of the params?
> I would like to do something like...
> declare @.c char(50)
> ,@.s char(30)
> set @.c = 'SomeClient'
> set @.s = 'SomeColumn'
> select @.s
> select *
> from MyTable
> where rtrim(clientName) = rtrim(@.c)
> order by rtrim(@.s)
>
> thanks in advance..
> bob.
>
DECLARE @.ClientName VARCHAR(50)
DECLARE @.ColumnName VARCHAR(30)
DECLARE @.Command VARCHAR(1024)
SELECT @.ClientName = 'SomeClient'
SELECT @.ColumnName = 'SomeColumn'
SELECT @.Command = 'SELECT * FROM MyTable WHERE clientName = @.ClientName
ORDER BY ' + @.ColumnName
EXEC (@.Command)|||http://www.aspfaq.com/2501
"John 3:16" <bobmcc@.tricoequipment.com> wrote in message
news:egtoAL7kGHA.4816@.TK2MSFTNGP05.phx.gbl...
> How do you allow sorting via one of the params?
> I would like to do something like...
> declare @.c char(50)
> ,@.s char(30)
> set @.c = 'SomeClient'
> set @.s = 'SomeColumn'
> select @.s
> select *
> from MyTable
> where rtrim(clientName) = rtrim(@.c)
> order by rtrim(@.s)
>
> thanks in advance..
> bob.
>|||Thanks Tracy...
I really appreciate it.
Bob.
"Tracy McKibben" <tracy@.realsqlguy.com> wrote in message
news:%23TIRzN7kGHA.5108@.TK2MSFTNGP02.phx.gbl...
> John 3:16 wrote:
> DECLARE @.ClientName VARCHAR(50)
> DECLARE @.ColumnName VARCHAR(30)
> DECLARE @.Command VARCHAR(1024)
> SELECT @.ClientName = 'SomeClient'
> SELECT @.ColumnName = 'SomeColumn'
> SELECT @.Command = 'SELECT * FROM MyTable WHERE clientName = @.ClientName
> ORDER BY ' + @.ColumnName
> EXEC (@.Command)|||Thanks Aaron...
I checked out the link....
I appreciate the reply and the link.
Bob.
"Aaron Bertrand [SQL Server MVP]" <ten.xoc@.dnartreb.noraa> wrote in message
news:upqE0N7kGHA.2052@.TK2MSFTNGP04.phx.gbl...
> http://www.aspfaq.com/2501
>
> "John 3:16" <bobmcc@.tricoequipment.com> wrote in message
> news:egtoAL7kGHA.4816@.TK2MSFTNGP05.phx.gbl...
>|||"John 3:16" <bobmcc@.tricoequipment.com> wrote in message
news:es2VKR7kGHA.4044@.TK2MSFTNGP03.phx.gbl...
> Thanks Tracy...
> I really appreciate it.
> Bob.
If your ORDER BY column name is not hard-wired into your script (highly
likely or you wouldn't need to use Dynamic SQL to generate the SELECT
statement), be very careful that you validate the column name thoroughly or
you can leave yourself open to SQL Injection, as in:
SELECT @.ColumnName = '1; TRUNCATE TABLE SomeImportantTable; --'

No comments:

Post a Comment