Solved

Select Statement with Order By as Parameter

Posted on 2010-09-10
7
273 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
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.

 

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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

I'm trying, I really am. But I've seen so many wrong approaches involving date(time) boundaries I despair about my inability to explain it. I've seen quite a few recently that define a non-leap year as 364 days, or 366 days and the list goes on. …
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 setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

733 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