Hello,
I'm writing an SP that should return a result set sorted by one, two, or
possibly more columns. The columns can be of different datatypes. The
sort order is determined by one, two, or possibly more input parameters.
should result in
ORDER BY Column1, Column2, etc. It is not known in advance how many sort
parameters may be specified.
I'm using the "orderbyvariable" technique by Richard Romley, the one with
multiple CASE statements in the ORDER BY clause. It works fine as long as
there is a single column (not counting NULLs) in the ORDER BY clause.
However, as soon as I modify my ORDER BY so that it handles the second
server doesn't like the fact that the same column name is listed more
than once in the ORDER BY clause, so I get error 169.
When there are only two sort levels, I can possibly work around this by
aliasing the columns in the SELECT statement, and using the aliases for
the first column in the ORDER BY, and base column names for the second.
Besides being a kludge, this doesn't handle the case when there are more
than two columns in the ORDER BY.
Here's the sample SP that doesn't compile. I'd appreciate any ideas on
how to make this work, or how to achieve what I'm looking for in some
other way. I cannot use dynamic SQL for this, and would prefer not to use
CAST to convert all columns to the same sortable datatype. I'm trying to
make this a generic solution that can be easily adapted to other SPs.
Thank you.
CREATE PROCEDURE procSelectInvoices
AS
SET NOCOUNT ON
SELECT i.InvoiceNumber,
i.InvoicedAmount,
i.InvoicedOn,
i.PostedOn
FROM tblInvoices AS i
WHERE 1 = 1 -- this is a sample
ORDER BY
THEN i.InvoiceNumber ELSE NULL END ASC,
THEN i.InvoiceNumber ELSE NULL END DESC,
THEN i.InvoicedAmount ELSE NULL END ASC,
THEN i.InvoicedAmount ELSE NULL END DESC,
THEN i.InvoicedOn ELSE NULL END ASC,
THEN i.InvoicedOn ELSE NULL END DESC,
THEN i.PostedOn ELSE NULL END ASC,
THEN i.PostedOn ELSE NULL END DESC,
THEN i.InvoiceNumber ELSE NULL END ASC,
THEN i.InvoiceNumber ELSE NULL END DESC,
THEN i.InvoicedAmount ELSE NULL END ASC,
THEN i.InvoicedAmount ELSE NULL END DESC,
THEN i.InvoicedOn ELSE NULL END ASC,
THEN i.InvoicedOn ELSE NULL END DESC,
THEN i.PostedOn ELSE NULL END ASC,
THEN i.PostedOn ELSE NULL END DESC
RETURN
DDL for tblInvoices:
CREATE TABLE tblInvoices (
InvoiceNumber varchar (20) NOT NULL,
InvoicedAmount money NOT NULL,
InvoicedOn smalldatetime NOT NULL,
PostedOn smalldatetime NULL
)
--
(remove a 9 to reply by email)