HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Printing simple SQL comparsion

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sqlsimplecomparsionprinting

Problem

I'm comparing two variables which I'd like to be printed to the console like so:

==Full Ex Vat==
true


Currently the code to do this is:

print '==Full Ex Vat=='
print case when
@aTotalExVat = @sTotalExVat
then 'true' else 'false' end


which 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 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'
      END


If you wanted to treat NULL = NULL as true and NULL = any not null value as false you could use

DECLARE @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'
      END
DECLARE @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.