Solved

Select Statement with Order By as Parameter

Posted on 2010-09-10
7
272 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
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
backup job space check 4 44
SQL create line numbers for data sampling 11 27
SQL USE DATABASE VARIABLE 5 27
Select question from MySQL 1 13
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.
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 extract information from SQL Server on Database, Connection and Server properties
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

861 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