klick.klonk klick.klonk - 3 months ago 14
SQL Question

Help with constructing a conditional SQL statement

I want to construct a SELECT statement with a conditional IF.

Like, IF there is no records with the language code

'Swedish'
:

SELECT * FROM Entries WHERE Language = 'Swedish'


THEN use
'English'


SELECT * FROM Entries WHERE Language = 'English'


How would I construct this statement using MSSQL?

Thanks,

Stefan

Answer

Naively:

SELECT *
FROM Entries
WHERE Language = 'Swedish' 

UNION ALL

SELECT *
FROM Entries
WHERE Language = 'English' 
    AND NOT EXISTS (
        SELECT *
        FROM Entries
        WHERE Language = 'Swedish' 
    )

or:

SELECT *
FROM Entries
WHERE Language = 'Swedish' 
    OR (Language = 'English' 
        AND NOT EXISTS (
            SELECT *
            FROM Entries
            WHERE Language = 'Swedish' 
        )
    )