Referencing a calculated column in the where clause SQL

六月ゝ 毕业季﹏ 提交于 2019-11-29 05:47:18

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

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!