Solved

Select Statement with Order By as Parameter

Posted on 2010-09-10
7
275 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
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

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. …
A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

705 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