Home Forums SQL Server 2008 T-SQL (SS2K8) Convert the stored procedure to "Standard SQL Select" RE: Convert the stored procedure to "Standard SQL Select"

  • SELECT

    [Open] = SUM(CASE WHEN DocStatus = 'Active' THEN 1 ELSE 0 END),

    [Closed] = SUM(CASE WHEN DocStatus = 'Retired' THEN 1 ELSE 0 END)

    FROM Document

    CROSS APPLY (

    SELECT

    CurrentDateFiscalYear = CASE WHEN MONTH(GETDATE()) < 11 THEN YEAR(GETDATE()) ELSE YEAR(GETDATE())+1,

    RetiredDateFiscalYear = CASE WHEN MONTH(RetiredDate) < 11 THEN YEAR(GETDATE()) ELSE YEAR(RetiredDate)+1

    ) x

    WHERE DocType = 1

    AND DocStatus IN ('Active','Retired')

    AND RetiredDateFiscalYear = CurrentDateFiscalYear

    -- you could greatly improve performance by calculating the start and end of the range of RetiredDate

    -- for any given value of GETDATE()

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden