patternsqlMinor
Printing simple SQL comparsion
Viewed 0 times
sqlsimplecomparsionprinting
Problem
I'm comparing two variables which I'd like to be printed to the console like so:
Currently the code to do this is:
which I feel isn't as elegant as it could be.
Any tips?
==Full Ex Vat==
trueCurrently the code to do this is:
print '==Full Ex Vat=='
print case when
@aTotalExVat = @sTotalExVat
then 'true' else 'false' endwhich I feel isn't as elegant as it could be.
Any tips?
Solution
SQL uses three valued logic.
When one of the operands is null the expression evaluates to
If you wanted to treat
On SQL Server 2012 there are a couple of new functions that shorten the above somewhat
When one of the operands is null the expression evaluates to
UNKNOWN not false. Your current code does not take account of this and can be altered as below to do so.PRINT CASE
WHEN @aTotalExVat = @sTotalExVat THEN 'true'
WHEN @aTotalExVat <> @sTotalExVat THEN 'false'
ELSE 'unknown'
ENDIf you wanted to treat
NULL = NULL as true and NULL = any not null value as false you could useDECLARE @Message VARCHAR(5) = CASE WHEN EXISTS(SELECT @aTotalExVat
INTERSECT
SELECT @sTotalExVat)
THEN 'true'
ELSE 'false'
END;
PRINT '==Full Ex Vat==';
PRINT @Message;On SQL Server 2012 there are a couple of new functions that shorten the above somewhat
DECLARE @Message VARCHAR(5) = IIF(EXISTS(SELECT @aTotalExVat
INTERSECT
SELECT @sTotalExVat),
'true',
'false');
PRINT CONCAT('==Full Ex Vat==', CHAR(13), ( CHAR(10) ), @Message);Code Snippets
PRINT CASE
WHEN @aTotalExVat = @sTotalExVat THEN 'true'
WHEN @aTotalExVat <> @sTotalExVat THEN 'false'
ELSE 'unknown'
ENDDECLARE @Message VARCHAR(5) = CASE WHEN EXISTS(SELECT @aTotalExVat
INTERSECT
SELECT @sTotalExVat)
THEN 'true'
ELSE 'false'
END;
PRINT '==Full Ex Vat==';
PRINT @Message;DECLARE @Message VARCHAR(5) = IIF(EXISTS(SELECT @aTotalExVat
INTERSECT
SELECT @sTotalExVat),
'true',
'false');
PRINT CONCAT('==Full Ex Vat==', CHAR(13), ( CHAR(10) ), @Message);Context
StackExchange Code Review Q#56320, answer score: 4
Revisions (0)
No revisions yet.