我正在嘗試創建一個存儲過程。 在where子句中比較三個日期值的最有效方法是什麼?tsql最有效的方法來比較where子句中的三個日期值?
例子:
tbl1.Date1,
tbl2.Date2, -- NOTE: Date2 can be NULL.
tbl3.Date3
示例數據:
Date1 Date2 Date3
2016-12-20 2016-11-21 2016-11-30
2016-11-21 NULL 2016-12-20
首先,我比較日期1和date2,我選擇 「做大」 的日期。 然後我比較這個「更大」的日期到Date3。 如果比較成立,我將值寫入表中。
-- This is simplified example:
INSERT INTO records
(
[user_date],
[user_name]
)
SELECT
tbl1.Date1,
tbl1.user_name
FROM
table1 AS tbl1
INNER JOIN table2 AS tbl2 ON tbl1.id = tbl2.id
INNER JOIN table3 AS tbl3 ON tbl2.id = tbl3.id
WHERE
-- I need to know what is bigger, Date1 or Date2, so I can compare correct date to Date3.
ISNULL(tbl2.Date2, tbl1.Date1) <= tbl3.Date3 -- ISNULL, doesn't work here, because Date2 and Date1 can get a value and comparison fails if Date1 is bigger than Date3.
AND ISNULL(tbl2.Date2, tbl1.Date1) > tbl3.last_date
在我的情況IIF是最好的解決方法=)謝謝! – 3volution