简体   繁体   中英

How to apply datediff function in select statement using case statement

I have a stored procedure to select columns of tables like this

CREATE PROCEDURE spSelect
AS
BEGIN
SELECT ID, CheckIn, 
LapsedDay = CASE WHEN Checkout = NULL THEN DATEDIFF(DAY, CheckIn, GETDATE ()) ELSE DATEDIFF(DAY, CheckIn, CheckOut) END, CheckOut FROM TblGuest 
END

whenever I am executing this query, it isn't showing any error but it's not calculating the the datediff in LapsedDay column in ms SQL. Any help related to this will be greatly appreciated.

= NULL is not correct. Comparisons to NULL almost always return NULL .

Just simplify the logic using COALESCE() :

SELECT ID, CheckIn, 
       DATEDIFF(DAY, CheckIn, COALESCE(CheckOut, GETDATE()) AS LapsedDay,
       CheckOut
FROM TblGuest 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM