views:

123

answers:

1

Ok, this may sound a little weird, but what I need to do is simple. I have a list of companies and each one has a description. The site is in 4 languages. My problem comes when I have listed a company in English but the person who is in charge of translating it in French still didn't make the translation, so I have a simple:

SELECT TOP(6)
    company.name,
    company.description,
    company.address
WHERE
    langid=1
ORDER BY
    company.id DESC

The real query is more complex, but I think it will be easier with this one to understand the problem. What I need to do is, when the description is empty in langid 2 then show me the langid 1 as langid 1 is always the first one that will be added. I don't want to show the description field empty.

Imagine row 1, row 2, row 3 and row 5 have a description for langid 2 but not row 4 and row 6. I need to show langid 2 for the rows containing it but langid 1 for the rows with no description.

I know that I could probably do a while with a @i field incrementing and inserting the results one by one in a temp table, but is there any better way of doing it?

+5  A: 

This will work unless there is lng1.name etc. (i.e. the English language/fallback variant) missing.

SELECT TOP(6) 
  COALESCE(lng2.name, lng1.name)               [name], 
  COALESCE(lng2.description, lng1.description) description, 
  COALESCE(lng2.address , lng1.address )       address
FROM 
  company lng1
  LEFT JOIN company lng2 ON 
    lng1.id     = lng2.id AND
    lng1.langid = 1 AND
    lng2.langid = 2  /* your "foreign language" id, e.g. a parameter */
WHERE
  lng1.id IN (1,2,3,4,5,6)  /* or whatever */
ORDER BY 
  lng1.id DESC

It will also not replace the entire address with the English/fallback version if only part of the localized variant is missing. Only the missing parts will be substituted.

Tomalak
COALESCE was the first thing that popped up in my mind as well...
Sung Meister
I have it in 2 tablesall common fields are in company table, the multilingual fields are in another table (one row per language, so in theory for every 1 row in company there are 5 rows in the multilingual one) Can i still apply COALESCE to solve it? as the name of the field is same on all langs
George
Of course. COALESCE returns the first of it's arguments that is not NULL. Where the arguments come from is irrelevant. A bit more detail in your question would have been nice - the info that you are using two tables comes a little late.
Tomalak