1

let's say I have a table with columns ID, Date1 and Date2 where Date2can be NULL. I now want to have an SQL statement that ignores Date2 if it is NULL.

So I need something like that:

SELECT *
FROM
  [myTable]
WHERE
  ID = @someId
  AND Date1 <= GETDATE()
  AND Date2 >= GETDATE() IF Date2 IS NOT NULL

So I want to check if Date2 is not NULL and then compare it with the current date. If it is NULL then I just want to ignore it.
Hope my request is clear and understandable.

Cheers
Simon

4

5 回答 5

3
AND Date1 <= GETDATE()
AND (Date2 IS NULL OR Date2 >= GETDATE() )

或者

AND Date1 <= GETDATE()
AND COALESCE(Date2, GETDATE()) >= GETDATE()-- which means : if Date2 IS NULL say Date2 = GETDATE()
于 2013-06-03T10:03:42.727 回答
2

AND (Date2 >= GETDATE() OR Date2 IS NULL)

于 2013-06-03T10:04:04.537 回答
1

试试这个 sql。

    SELECT *
    FROM yourtable
    WHERE ID = @someId
    AND Date1 <= GETDATE()
    AND (Date2 IS NULL
    AND Date2 >= GETDATE());
于 2013-06-03T10:15:53.727 回答
1

你可以这样做:

ISNULL(Date2, GETDATE()) >= GETDATE() 
于 2013-06-03T10:10:14.740 回答
0
SELECT *
FROM
  [myTable]
WHERE
  ID = @someId
  AND Date1 <= GETDATE()
  AND Date2 NOT IS NULL
  AND Date2 >= GETDATE();
于 2013-06-03T10:13:27.697 回答