Shorter CASE ISNULL(qry, '')='' THEN 'no' ELSE 'yes' END

1.5k views Asked by At

Is there a shorter/better way to write this SQL statement?

Edit: the inner sql select statement is a placeholder, the actual statement is more complex.

SELECT
    CASE WHEN
        ISNULL((SELECT TOP 1 x FROM y), '') = ''
    THEN 'No'
    ELSE 'Yes'
    END AS BooleanValue

It feels very kludgey because it compares the result of the select statement to null, then sets to an empty string if null; just to check if it is an empty string, and set it to what it actually needs to be: a 'yes' or 'no' string.

2

There are 2 answers

0
abaldwin99 On BEST ANSWER

Here's one way to do it a bit cleaner.

SELECT
    CASE WHEN
        (SELECT TOP 1 x FROM y) IS NULL
    THEN 'No'
    ELSE 'Yes'
    END AS BooleanValue

This removes one extra command and should have the same output. I just tested it in sql server 2012.

0
Peter On
SELECT ISNULL((SELECT TOP 1 'Yes' FROM x), 'No') as Boolean