13

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 ....

7
  • @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 K
    Apr 21, 2010 at 13:44
  • Also NULL, because any implies none.
    – ercan
    Apr 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 K
    Apr 21, 2010 at 13:54
  • The real question might be: What is returned if the list is empty?
    – John K
    Apr 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...
    – ercan
    Apr 21, 2010 at 14:06

5 Answers 5

6

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
2
6

Since NULLs propogate you could do:

(cola + colb + colc) is null

assuming all compatible data types

2
  • 1
    That's why I put the constraint of any type in the post ;)
    – ercan
    Apr 21, 2010 at 14:33
  • Maybe you could coerce them into a single type, since the values themselves don't matter for the test. Maybe a nullable bit?
    – tloflin
    Apr 22, 2010 at 16:46
1

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.

1
  • 1
    Actually, NULLIF returns NULL if the two input-parameters are the same. I don't see any way to achieve this with cascaded NULLIFs.
    – ercan
    Apr 21, 2010 at 13:59
0

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
1
  • 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
    – ercan
    Apr 23, 2010 at 8:16
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.