Skip to content
Advertisement

How to perform Case statement inside a select statement?

I wanted to put ‘No record’ on the column instead of NULL if the datediff function returns a null value.

So far this code only throws Incorrect syntax near ‘CAST’, expected ‘AS’. but I don’t know what data type should I put in the CAST parameter , since if there’s a record it will show the datetime .

Advertisement

Answer

Strictly answering question (though I don’t understand why you need a CASE expression if you have working versions of the query), you can easily translate this to a CASE expression:

ISNULL really is just nice, convenient shorthand for CASE WHEN a IS NOT NULL THEN a ELSE b END, so:

As you can see, a downside is that if you really really really want a CASE expression, you have to repeat at least the DATEDIFF to cover both the case where the outer row doesn’t exist and the case where the outer row exists but one of the values is NULL.

Also note that you should always specify a length for variable types like varchar, even in cases where you think you’re safe with the default.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement