is there a function in SQL Server 2005 that returns NULL [or a boolean value] if any of the arguments (of any type) is NULL, which would save me from writing IF a IS NULL OR b IS NULL OR c IS NULL ...
.
-
@Michael B: Likely the last item in the list since it's not null and will suffice. The focus is NULL so although a non-NULL value is important, the actual value is irrelevant.– John KApr 21, 2010 at 13:44
-
Also NULL, because any implies none.– ercanApr 21, 2010 at 13:45
-
@ecran: (Assuming your comment is a response to @Michael B), Wouldn't that defeat the purpose of the function you want, if you return null when no null is present? I mean the function would always return null.– John KApr 21, 2010 at 13:54
-
The real question might be: What is returned if the list is empty?– John KApr 21, 2010 at 13:56
-
@jdk: Actually, it was a mistake that I said NULL must be returned. A boolean return value would suffice (like OR returns). 1 for no NULLs in parameter-list and 0 if any NULLs, or vice versa...– ercanApr 21, 2010 at 14:06
5 Answers
Here is a moderately unpleasant way of doing it:
set ansi_nulls off
if (null in (a, b, c, d, e) print 'got a null'
set ansi_nulls on
-
6
-
A stern caution from Microsoft that NULL can produce unexpected results in this scenario: msdn.microsoft.com/en-us/library/ms177682.aspx– John KApr 21, 2010 at 14:29
Since NULLs propogate you could do:
(cola + colb + colc) is null
assuming all compatible data types
-
1
-
Maybe you could coerce them into a single type, since the values themselves don't matter for the test. Maybe a nullable bit?– tloflinApr 22, 2010 at 16:46
No, the closest you an get is NULLIF(), but that's not what you want. I'd just stick to using the OR statement here.
-
1Actually, NULLIF returns NULL if the two input-parameters are the same. I don't see any way to achieve this with cascaded NULLIFs.– ercanApr 21, 2010 at 13:59
How about ...
SELECT
CASE WHEN NULLIF(ISNULL(@testA, 1), @testA)
+ NULLIF(ISNULL(@testB, 1), @testB)
+ NULLIF(ISNULL(@testC, 1), @testC) > 0
THEN 'Got NULL'
ELSE 'NO NULL'
END
-
This takes care of the "of any type" constraint, but for the sake of readability, I would prefer
@testA IS NULL OR @testB IS NULL OR @testC IS NULL
– ercanApr 23, 2010 at 8:16
I am not sure of SQL Server, but in similar database (I used hive here which is more close to traditional DBMS in terms of syntax) select isnull(concat(*)) from some_table;
would help to check if any of the column is NULL
.
Hope there is some way to play around this concept in SQL Server and my suggestion helps to solve the problem efficiently.