Solved

Select Statement with Order By as Parameter

Posted on 2010-09-10
7
266 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
ID: 33648639
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
ID: 33648691
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
ID: 33648703
Sorry forgot @ in variable statementValue, use @statementValue
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 

Author Comment

by:yonbret
ID: 33648794
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
ID: 33648806
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
ID: 33648814
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
ID: 33649095
Works great
0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have a large data set and a SSIS package. How can I load this file in multi threading?
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

863 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

23 Experts available now in Live!

Get 1:1 Help Now