Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if exactly one variable is not null

In a trigger in my sql-server 2008 database I need to check if exactly one variable is not null. This code does what I need, but can it be done in fewer lines and more readable?

DECLARE @string varchar
DECLARE @float float
DECLARE @bit bit
DECLARE @int int

Set @string=NULL  -- Exactly one of these variables needs to be set
Set @float=NULL   --
Set @bit=NULL     -- 
Set @int=NULL     --

IF(   (@string is not null AND COALESCE(@float, @bit, @int) IS NULL)
    OR (@float is not null AND COALESCE(@string, @bit, @int) IS NULL)
    OR (@bit is not null AND COALESCE(@string, @float, @int) IS NULL)
    OR (@int is not null AND COALESCE(@string, @float, @bit) IS NULL)
)
print ' ok'
ELSE 
print ' not ok'
like image 750
grimmig Avatar asked Apr 07 '11 09:04

grimmig


People also ask

How do you check if something is not null in JavaScript?

Typically, you'll check for null using the triple equality operator ( === or !== ), also known as the strict equality operator, to be sure that the value in question is definitely not null: object !== null . That code checks that the variable object does not have the value null .

IS NOT NULL function in Java?

The method isNull is a static method of the Objects class in java that checks whether the input object reference supplied to it is null or not. If the passed object is null , then the method returns true . If the passed object is non-null , then the method returns false .

How do I check if a variable is null in typescript?

We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.


2 Answers

SELECT CASE WHEN COUNT(c) =1 THEN 'Y' ELSE 'N' END
FROM 
(VALUES (CAST(@string AS SQL_VARIANT)),(@float),(@bit),(@int)) T (c) 
like image 63
Martin Smith Avatar answered Sep 30 '22 16:09

Martin Smith


I'm not necessarily sure it's any more readable (although I guess if you abstracted it to a function it might be) but

if((case when @string is null then 0 else 1 end + 
    case when @float  is null then 0 else 1 end +
    case when @bit    is null then 0 else 1 end + 
    case when @int    is null then 0 else 1 end) = 1) 
  .... 

is a little more flexible?

like image 36
Unsliced Avatar answered Sep 30 '22 18:09

Unsliced