Avatar of woodwyn
woodwyn
Flag for United States of America

asked on 

How to use variables passed to a SQL stored procedure in the Order By clause

FYI, this client is running an old site still using SQL 2000 as the backend database.  We'll be upgrading them to SQL 2016 soon.  

Here are parts the stored procedure.  You can see they want to pass up to 5 variables that may be used to sort the data.  It will be common that none or less then 5 order by variables will be passed to the stored procedure.  I.e., @cSortBy1 may contain

CREATE PROCEDURE [EOLReportOrderHistory]
      @cKeyWebSubDomains UNIQUEIDENTIFIER,
      @dStartDate SMALLDATETIME,      
      @dEndDate SMALLDATETIME,
      @cWebSubDomainsMenusKeys varchar(8000),      -- Keys will be seperated by a comma
      @cOrderNumber char(8),                        -- Search dbo.WebOrders.OrderNumber for this string
      @cOrderDescription varchar(8000),            -- Search UniqueID questions for this string
      @nIsPDF TinyInt,                        -- Will this data be used for a PDF report of Excel spreadsheet
      @cSortBy1 char(200),                  -- Sort By parameter 1
      @cSortBy2 char(200),                  -- Sort By parameter 2
      @cSortBy3 char(200),                  -- Sort By parameter 3
      @cSortBy4 char(200),                  -- Sort By parameter 4
      @cSortBy5 char(200)                  -- Sort By parameter 5
AS
...
SELECT
        Customer = QUOTENAME(RTRIM(Customer),''''),
      TopMenu = RTRIM((SELECT LeftMenuHeader FROM WebSubDomainsMenus WHERE WebSubDomainsMenus.keyWebSubDomainsMenus=#MSR1.keyTopMenu)),
      OrderNumber = OrderNumber,
        OrderDescription,
        DateCreated,
        UserName,
        RTRIM(ShortDescription),
        Qty, Price, Qty*Price AS ItemTotal,
      ISNULL((SELECT OrderTotal FROM #MSR2 WHERE #MSR2.keyWebOrder=#MSR1.keyWebOrder),0) AS OrderTotal,
      ISNULL((SELECT CategoryTotal FROM #MSR3 WHERE #MSR3.keyTopMenu=#MSR1.keyTopMenu),0) AS CategoryTotal,
      GrandTotal = @nTotalSales
FROM #MSR1
ORDER BY @cSortBy1, @cSortBy2, @cSortBy3, @cSortBy4, @cSortBy5, CategorySort, OrderNumber

The stored procedure will have default Order By columns CategorySort, OrderNumber
Microsoft SQL Server

Avatar of undefined
Last Comment
woodwyn

8/22/2022 - Mon