Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: how to return 1 row as default if condition not met

I have a table of messages that contains a message id field, a language id field and a text field. An app needs to display a message based on the id and language which together form the unique key. All messages exist for language EN, but not all have been translated to other languages. So for English there will always be one record selected. But if the user is French and the app needs to display message #17 and it doesn't exist yet for French, I want to return message #17 in EN. I would like to accomplish this in one SELECT query, preferably with no IF Statements.

EDIT: based on the answers submitted - need to clarify that every message is translated to about 10 languages, maybe more. there should always be exactly one row returned based on the message id and the lang id. but if that row doesnt exist, the english message should be returned.

The final code:
declare @msgid int=2, @langid varchar(2)='fr' SELECT isnull(xx.msg, en.msg) msgtext FROM appmessages en LEFT JOIN appmessages xx ON en.msgid = xx.msgid and xx.langid=@langid WHERE en.langid = 'en' and en.msgid=@msgid

like image 909
lvk Avatar asked Dec 17 '15 16:12

lvk


1 Answers

You can use a LEFT JOIN and ISNULL to achieve this

SELECT
    ISNULL(fr.message, en.message) AS message
FROM message_table en
LEFT JOIN message_table fr ON
    fr.message_id = en.message_id
    AND fr.language = 'French'
WHERE 
    en.message_id = 17
    AND en.language = 'English'
like image 94
Chris Stillwell Avatar answered Nov 14 '22 21:11

Chris Stillwell