SQL Comparison of Dates

时间:2016-04-04 18:35:29

标签: sql sql-server

Okay, I have a situation when I need to compare a column from a table with today's date. If the value in a particular row is earlier than today (in other words, the date has already passed, I need to mark a virtual column with the phrase 'lapsed'

Below is the SQL (SQL Server 2012) that I have been using:

SELECT
 datediff(day, sysdatetime(), policy_expiration_dt) As 'DayDiff'
,Case When 'DayDiff' < 0 Then 'Lapsed' 
FROM TABLE_NAME

The first column that includes the datediff function makes the comparison and the second column marks it as lapsed if the date has passed.

1 个答案:

答案 0 :(得分:-1)

basically the order of how an sql statement is executed does not allow you to use the alias. so you will need to use the datediff() function in the CASE statement.

The order of sql queries execution is:

1. FROM
2. ON
3. OUTER
4. WHERE
5. GROUP BY
6. CUBE | ROLLUP
7. HAVING
8. SELECT
9. DISTINCT
10. ORDER BY
11. TOP

you need to do this:

SELECT DATEDIFF(day, SYSDATETIME(), policy_expiration_dt) AS 'DayDiff'
    , CASE
         WHEN DATEDIFF(day, SYSDATETIME(), policy_expiration_dt)  < 0 THEN 'Lapsed'
      END
FROM   TABLE_NAME;