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'
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 .
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 .
We can use typeof or '==' or '===' to check if a variable is null or undefined in typescript.
SELECT CASE WHEN COUNT(c) =1 THEN 'Y' ELSE 'N' END
FROM
(VALUES (CAST(@string AS SQL_VARIANT)),(@float),(@bit),(@int)) T (c)
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With