Link to home
Start Free TrialLog in
Avatar of chandua
chandua

asked on

Stored Procedure - Passing order by string as parameter

hi
i want to order the record dynamically..want to pass the order by string at runtime to the SP.

tried with the code below.. it doesn't work..
select clentname,add1 from client
order by ' + @OrderBy + '

the @orderby parameter has the fieldname..(clientname or add1)

Avatar of peterdownes
peterdownes

TRY:

EXEC ('select clentname, add1 from client order by ' + @OrderBy)
Hi,
Try this code. This will work.
I tried to use the variable @fldname in the order by clause. it gave me an error. Finally I did like this. This code is ok and feasible only when few order by changes are there. I mean when order by clause changes twice or thrice. Mean while, let me see whether we can pass a variable and achieve the same thing n number of times.

create procedure deleteme @fldname varchar(10)
as
declare @fld varchar(10)
select @fld=@fldname
if @fld ='clientname'
     select * from tablename order by clientname
if @fld = 'add1'
     select * from tablename order by add1
return

You have to concatinate the string first, that's why answer 1 doesn't work. And answer 2 requires a separate if statement for every field, and if you want to order by 2 fields - well the combinations go on for ever.

i.e

create proc yada
(
   @orderby nvarchar(20)
)
as
declare @temp nvarchar(200)
set @temp = 'select * from tblBlah order by ' + @orderby
exec(@temp)
go

--example usage:
yada 'fieldA desc,fieldC'
--or even
yada 'fieldA'
ASKER CERTIFIED SOLUTION
Avatar of peterdownes
peterdownes

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is true, I'm trying to think why I had a problem with the exec statement a while back.. Never mind, ignore my ramblings.
Avatar of chandua

ASKER

hi tried foll query it still doesn't work. the diff is iam using a where clause.
if i take out the where clause the order by workss fine
CREATE PROCEDURE dbo.sp_test
     @orderby varchar(30),
     @Country varchar(50)
as
exec('select * from tblcountry where country=@country order by' + @orderby)


CREATE PROCEDURE dbo.sp_test
    @orderby varchar(30),
    @Country varchar(50)
as
exec('select * from tblcountry where country=''' + @country + ''' order by ' + @orderby)

Cut and paste that...
Avatar of chandua

ASKER

it still doesn't work fine for me if i have many parameters to my query.. i tried the same method for the foll query, but this one is for passing parameter for the Database name

CREATE PROCEDURE dbo.SPRetUser
@DBName as varchar(20)
AS
exec('select * from ''' + @DBName + '''+tblUser')
GO

my query shld look somethin like this

select * from SOSCase.Dbo.tblUser
pls help me to get the above query

i have increased the points.. to 100 as i feel i am asking too many questions for 15 points.

OK, this query should be:

exec('select * from ' + @DBName + '.tblUser')

if you pass SOSCase.Dbo in @DBName.

Regards.

Avatar of chandua

ASKER

okie thanks. it works fine for the DBName. but my previous query for Order By still doesn't work.
here is the code again..

___________________________________________________________
CREATE PROCEDURE dbo.SPTest
      @Fname varchar(50),
      @FromDate smalldatetime,
      @ToDate smalldatetime,
      @selection varchar(50)
As
exec('select * from tblUser where
UserFName = like '''+ @Fname + ''' + ''' + '%' + ''' and  
UserBirthDate between ''' + @FromDate + ''' and ''' + @ToDate + '''
order by ' + @selection)___________________________________________________________

it works well for other parameters except the date, for example:
SPTest '','01/01/1900','01/01/2010','UserFName'
it will always give me the error"
Server: Msg 295, Level 16, State 3, Line 1
Syntax error converting character string to smalldatetime data type.

pls help me to find the solution, thanks a lot



Try:

CREATE PROCEDURE SPTest
   @Fname varchar(50),
   @FromDate smalldatetime,
   @ToDate smalldatetime,
   @Selection varchar(50)
AS
   DECLARE @strTmp varchar(800)

   SET @strTmp = 'select * from tblUser where UserFName like ' + '"' + @Fname + '%" AND UserBirthDate BETWEEN "' + CONVERT(varchar, @FromDate, 106) + '" AND "' + CONVERT(varchar, @ToDate, 106) + '" ORDER BY ' + @Selection

   EXEC (@strTmp)
Avatar of chandua

ASKER

hi peterdownes,

i think i need to understand why so many quotes are passed.
b'cos for diff datatype its giving errors. lastime it was for date parameter & now if i have a integer (int) value. it gives me the error.
here is the code iam trying

CREATE PROCEDURE dbo.SPtest10
@CountID int
AS
declare @string varchar(500)
set @string = 'select * from tblCurrency
where countid=''' + @CountID + ''' '
exec(@string)
GO

pls help...
Perhaps you would like to reject the proposed answer.
It is rare to lock questions on this forum and they do not get looked at often.

I haven't bothered to read the thread as it is locked but:

Only character variables need to have the value enclosed in quotes.

so

set @string = 'select * from tblCurrency
where string = ''' + @var + ''' '

set @string = 'select * from tblCurrency
where number = ' + @var

will give (for 123 in the @var)
select * from tblCurrency where string = '123'
select * from tblCurrency where number = 123

For your original question
>> select clentname,add1 from client
>> order by ' + @OrderBy + '
>> @orderby (clientname or add1)

select clentname,add1 from client
order by case when @OrderBy = 'clientname' then  clientname else null end, add1

or if they are the same datatype
select clentname,add1 from client
order by case when @OrderBy = 'clientname' then  clientname else add1 end
As nigelrivett has explained, you only need to place quotes around string values.

Well nearly!

As you can see from you SPTest with smalldatetime parameters, I converted them to 106 format -> dd mon yyyy.  So you also need to place quotes around this.  If you converted it to say dd/mm/yyyy format, the quotes wouldn't of been necessary.

As ruperts explain earlier, nigelrivett's CASE statement means you need to address all possiblilties, not just clientname and add1.  If this is what you want to do, then it removes the need to use the EXEC statement, and therefore all those confusing quotes.
     
Regards.

47 questions asked, only 22 closed.... ADMINISTRATION WILL BE CONTACTING YOU SHORTLY.
This question appears to have been abandoned. Your options are:
 
1. Accept a Comment As Answer (use the button next to the Expert's name).
2. Close the question if the information was not useful to you. You must tell the participants why you wish to do this, and allow for Expert response.
3. Ask Community Support to help split points between participating experts, or just comment here with details and we'll respond with the process.
4. Delete the question. Again, you must tell the other participants why you wish to do this.

For special handling needs, please post a zero point question in the link below, include the question QID/link.
https://www.experts-exchange.com/jsp/qList.jsp?ta=commspt
 
Please click this Help Desk link for Member Guidelines, Member Agreement and the Question/Answer process:  Click you Member Profile to view your question history and keep them all current with updates as the collaboration effort continues.
https://www.experts-exchange.com/jsp/cmtyHelpDesk.jsp

To view your open questions, please click the following link(s) and update/finalize them all.

https://www.experts-exchange.com/jsp/qShow.jsp?ta=crystal&qid=20223690
https://www.experts-exchange.com/jsp/qShow.jsp?ta=crystal&qid=20265178
https://www.experts-exchange.com/jsp/qShow.jsp?ta=crystal&qid=20265195
https://www.experts-exchange.com/jsp/qShow.jsp?ta=crystal&qid=20274444
https://www.experts-exchange.com/jsp/qShow.jsp?ta=crystal&qid=20275198
https://www.experts-exchange.com/jsp/qShow.jsp?ta=crystal&qid=20180838
https://www.experts-exchange.com/jsp/qShow.jsp?ta=mssql&qid=20133711
https://www.experts-exchange.com/jsp/qShow.jsp?ta=mssql&qid=20267928
https://www.experts-exchange.com/jsp/qShow.jsp?ta=mssql&qid=20272203
https://www.experts-exchange.com/jsp/qShow.jsp?ta=mssql&qid=20268833
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20273717
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20271488
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20271453
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20266279
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20264617
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20258796
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20257478
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20255754
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20255748
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20242197
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20214627
https://www.experts-exchange.com/jsp/qShow.jsp?ta=visualbasic&qid=20193125
https://www.experts-exchange.com/jsp/qShow.jsp?ta=asp&qid=20181410
https://www.experts-exchange.com/jsp/qShow.jsp?ta=asp&qid=20148274
https://www.experts-exchange.com/jsp/qShow.jsp?ta=asp&qid=20008099

PLEASE DO NOT AWARD THE POINTS TO ME.  
 
------------>  EXPERTS:  Please leave any comments regarding this question here on closing recommendations if this item remains inactive another three days.
 
Thank you everyone.
 
Moondancer
Moderator @ Experts Exchange

P.S.  For year 2000 questions, special attention is needed to ensure the first correct response is awarded, since they are not in the comment date order, but rather in Member ID order.
EXPERT INPUT PLEASE ..... SINCE CHANDUA CLEARLY IGNORES REQUESTS TO MANAGE QUESTIONS.

I WILL CLOSE THIS, TELL ME WHOM TO AWARD; LET ME KNOW IF SOME POINT SPLITS WOULD BE MORE APPROPRIATE OR ONE RESPONSE IS TO BE AWARDED.

THANKS,

MOONDANCER - EE MODERATOR
Zero response from ANYONE, finalized.
Moondancer - EE Moderator