Solved

Select Statement with Order By as Parameter

Posted on 2010-09-10
7
263 Views
Last Modified: 2012-05-10
I am trying to pass the stored procedure two varaibles @SortColumn, @SortDirection

How can I make this happen?

The code below will not work with the parameters.

How do I include a parameter in an Order By clause?

select LTrim(RTrim(D.SONo)) [SalesOrder], D.tranlineno [Line], L.Location AS Customer,
S.item, Cast(S.origqtyord as float) AS OrderQty, D.Serials [Allocated], S.rqdate AS DueDate,
S.ponum2 AS PO
from data as D
Inner Join dbo.SageProSOTRAN01 AS S on LTrim(RTrim(S.SONo)) = LTrim(RTrim(D.SONo)) and  S.tranlineno = D.tranlineNo
INNER JOIN dbEnterprise.dbo.tbCustomerLocation AS L ON L.CustNo = S.custno
INNER JOIN dbo.SageProSOADDR01 AS SA ON S.sono = SA.sono AND L.CShipNo = SA.cshipno
where (S.ordate >= GETDATE() - 30)
Order By @SortColumn + ' ' + @SortDirection
0
Comment
Question by:yonbret
7 Comments
 
LVL 3

Expert Comment

by:ghayasurrehman
Comment Utility
use this
declare @sql varchar(max)


set @sql = 'select LTrim(RTrim(D.SONo)) [SalesOrder], D.tranlineno [Line], L.Location AS Customer,
S.item, Cast(S.origqtyord as float) AS OrderQty, D.Serials [Allocated], S.rqdate AS DueDate,
S.ponum2 AS PO
from data as D
Inner Join dbo.SageProSOTRAN01 AS S on LTrim(RTrim(S.SONo)) = LTrim(RTrim(D.SONo)) and  S.tranlineno = D.tranlineNo
INNER JOIN dbEnterprise.dbo.tbCustomerLocation AS L ON L.CustNo = S.custno 
INNER JOIN dbo.SageProSOADDR01 AS SA ON S.sono = SA.sono AND L.CShipNo = SA.cshipno
where (S.ordate >= GETDATE() - 30)
Order By' + @SortColumn + ''' ''' + @SortDirection

exec SP_EXECUTESQL  @sql

Open in new window

0
 
LVL 4

Expert Comment

by:birdmian
Comment Utility
I think you can not use parametrs in ORDER BY aspecially using cast to string like this: @SortColumn + ' ' + @SortDirection. But mybe i am wrong
You can try to use dynamic SQL and EXEC, but use it carefully and in this case it can execute slowly.
Look like this:

DECLARE
      statementValue varchar(1000)
      
select statementValue =
'select LTrim(RTrim(D.SONo)) [SalesOrder], D.tranlineno [Line], L.Location AS Customer,
S.item, Cast(S.origqtyord as float) AS OrderQty, D.Serials [Allocated], S.rqdate AS DueDate,
S.ponum2 AS PO
from data as D
Inner Join dbo.SageProSOTRAN01 AS S on LTrim(RTrim(S.SONo)) = LTrim(RTrim(D.SONo)) and  S.tranlineno = D.tranlineNo
INNER JOIN dbEnterprise.dbo.tbCustomerLocation AS L ON L.CustNo = S.custno
INNER JOIN dbo.SageProSOADDR01 AS SA ON S.sono = SA.sono AND L.CShipNo = SA.cshipno
where (S.ordate >= GETDATE() - 30)
Order By ' + @SortColumn + ', ' + @SortDirection

EXEC (statementValue)
0
 
LVL 4

Expert Comment

by:birdmian
Comment Utility
Sorry forgot @ in variable statementValue, use @statementValue
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:yonbret
Comment Utility
One small wrinkle

I have the following code before the Select Statement listed above:

with data as (select t1.SONo, t1.tranlineNo, t1.origqtyord
         , sum(case when t2.SerialNumber is not null then 1 else 0 end) serials
   from SageProSOTRAN01 t1
   left join tbSerialNumberShipment t2
     on LTrim(RTrim(t1.SONo)) = t2.SalesOrder and  t1.tranlineno = t2.LineNumber
      Where (t1.item NOT LIKE 'dsq%') AND
              (t1.item NOT LIKE 'waq%') AND
              (t1.item NOT LIKE 'lcq%')
   group by t1.SoNo, t1.tranlineNo, t1.origqtyord)

When I try to set the Select statement as text, I am getting a syntax error at the declare variable line.

The entire code I currently have is:


with data as (select t1.SONo, t1.tranlineNo, t1.origqtyord

         , sum(case when t2.SerialNumber is not null then 1 else 0 end) serials

   from SageProSOTRAN01 t1

   left join tbSerialNumberShipment t2

     on LTrim(RTrim(t1.SONo)) = t2.SalesOrder and  t1.tranlineno = t2.LineNumber

	Where (t1.item NOT LIKE 'dsq%') AND 

		  (t1.item NOT LIKE 'waq%') AND 

		  (t1.item NOT LIKE 'lcq%')

   group by t1.SoNo, t1.tranlineNo, t1.origqtyord)



	declare @sql varchar(max)



	set @sql = 'select LTrim(RTrim(D.SONo)) [SalesOrder], D.tranlineno [Line], L.Location AS Customer,

	S.item, Cast(S.origqtyord as float) AS OrderQty, D.Serials [Allocated], S.rqdate AS DueDate, S.ponum2 AS PO

	    from data as D

		Inner Join dbo.SageProSOTRAN01 AS S on LTrim(RTrim(S.SONo)) = LTrim(RTrim(D.SONo)) and  S.tranlineno = D.tranlineNo

		INNER JOIN dbEnterprise.dbo.tbCustomerLocation AS L ON L.CustNo = S.custno 

		INNER JOIN dbo.SageProSOADDR01 AS SA ON S.sono = SA.sono AND L.CShipNo = SA.cshipno

	 where

	(S.ordate >= GETDATE() - 30)

	Order By' + @SortColumn + ''' ''' + @SortDirection





exec SP_EXECUTESQL  @sql

Open in new window

0
 
LVL 11

Accepted Solution

by:
Larissa T earned 500 total points
Comment Utility
We use it without dynamic sql using case. Works OK with SQL 2000.
Don't forget to ad last one without case. It would be your default sort
...
order by       
                  case when @orderBy = 'name' then cm.coname end,
                  case when @orderBy = 'name desc' then cm.coname end desc,
                  case when @orderBy = 'ratingdt' then ratingdt end,
                  case when @orderBy = 'ratingdt desc' then ratingdt end desc,
                  case when @orderBy = 'total_exposure' then total_exposure  end,
                  case when @orderBy = 'total_exposure desc' then total_exposure  end desc,
                  cm.coname
0
 
LVL 5

Expert Comment

by:jijeesh
Comment Utility
modify below query as per your requirement

USE AdventureWorks
GO
DECLARE @OrderBy VARCHAR(10)
DECLARE @OrderByDirection VARCHAR(1)
SET @OrderBy = 'State' ----Other options Postal for PostalCode,
---- State for StateProvinceID, City for City
SET @OrderByDirection = 'D' ----Other options A for ascending,
---- D for descending
SELECT AddressID, City, StateProvinceID, PostalCode
FROM person.address
WHERE AddressID < 100
ORDER BY
CASE WHEN @OrderBy = 'Postal'
AND @OrderByDirection = 'D'
THEN PostalCode END DESC,
CASE WHEN @OrderBy = 'Postal'
AND @OrderByDirection != 'D'
THEN PostalCode END,
CASE WHEN @OrderBy = 'State'
AND @OrderByDirection = 'D'
THEN StateProvinceID END DESC,
CASE WHEN @OrderBy = 'State'
AND @OrderByDirection != 'D'
THEN StateProvinceID END,
CASE WHEN @OrderBy = 'City'
AND @OrderByDirection = 'D'
THEN City END DESC,
CASE WHEN @OrderBy = 'City'
AND @OrderByDirection != 'D'
THEN City END
GO
0
 

Author Closing Comment

by:yonbret
Comment Utility
Works great
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Join & Write a Comment

If you find yourself in this situation “I have used SELECT DISTINCT but I’m getting duplicates” then I'm sorry to say you are using the wrong SQL technique as it only does one thing which is: produces whole rows that are unique. If the results you a…
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now