Referencing a calculated column in the where clause SQL

后端 未结 2 1274
滥情空心
滥情空心 2020-12-17 14:35

This line of code is a snippet from my select statement.

frdFreedays - DateDiff(dd,conReceiptToStock,GetDate()) As FreeDaysRemaining

Below

相关标签:
2条回答
  • 2020-12-17 15:08

    In addition to Aaron's answer, you could use a common table expression:

    ;with cte_FreeDaysRemaining as
        (
            select
                frdFreedays - DateDiff(dd,conReceiptToStock,GetDate()) As FreeDaysRemaining
                --, more columns
            from yourtable
        )
        select
            FreeDaysRemaining
            --, more columns
        from cte_FreeDaysRemaining
        where FreeDaysRemaining <= @intFreeDays
    
    0 讨论(0)
  • 2020-12-17 15:11

    You can't reference an alias anywhere except ORDER BY. One workaround (aside from the obvious possibility of repeating the expression) is to put it in a derived table:

    SELECT FreeDaysRemaining --, other columns
    FROM
    (
      SELECT frdFreedays - DATEDIFF(DAY, conReceiptToStock, GETDATE()) AS FreeDaysRemaining
        --, other columns
      FROM ...
    ) AS x
    WHERE FreeDaysRemaining <= @intFreeDays;
    
    0 讨论(0)
提交回复
热议问题