Case

用案例替換查詢結果/失敗時

  • February 20, 2014

使用 MS SQL,我喜歡在 Item translation (IT).Description 列為 NULL 並且客戶 C 的語言設置時替換 OEM_Description 列中的資訊。

$$ Language Code $$是英文 (ENG) 到原始項目描述 (I.$$ Description $$) 我提出了這個查詢:

SELECT
   "OEM_Description" = 
CASE 
  WHEN  (C.[Language Code] = 'ENG' and IT.[Description] = NULL)
  THEN I.[Description]
 ELSE IT.[Description]
END,
C.Name as Customer_Name

但是,僅當我在“C.

$$ Language Code $$= ‘ENG’" 一旦我添加了 IT 測試。$$ Description $$= NULL 什麼都沒有被替換。 我錯了什麼?

你沒有提到什麼 DBMS,但你可能需要IS NULL而不是= NULL. 但是,當這是教科書的使用時,您正在創建一個複雜的案例COALESCE ()

SELECT
   "OEM_Description" = COALESCE( IT.[Description], I.[Description] ),
   C.Name as Customer_Name

基於評論的替代解決方案:

IS NULL 不是一個函式= NULL,而是你原來的替代品,如下所示:

SELECT
   "OEM_Description" = 
CASE 
  WHEN  (C.[Language Code] = 'ENG' and IT.[Description] IS NULL)
  THEN I.[Description]
 ELSE IT.[Description]
END,
C.Name as Customer_Name

引用自:https://dba.stackexchange.com/questions/59289