在计算列公式中使用 CASE WHEN 分配列值时出现语法错误

Syntax error when assigning column value using CASE WHEN in Computed Column Formula

我试图在计算列别名中使用以下 CASE WHEN,但它显示语法错误。

[Password_Last_Changed] [datetime] AS
SELECT CASE
WHEN ([SUA_History1_Date] IS NOT NULL) then [SUA_History1_Date]
WHEN ([SUA_History1_Date] IS NULL) then [SUA_History2_Date]
WHEN ([SUA_History2_Date] IS NULL) then [SUA_History3_Date] 
WHEN ([SUA_History3_Date] IS NULL) then [SUA_History4_Date] 
WHEN ([SUA_History4_Date] IS NULL) then [SUA_History5_Date]
ELSE NULL 
END

不确定哪里出了问题。如果这个逻辑有更好的方法,请让我试试。

您可以使用 COALESCE:

COALESCE([SUA_History1_Date],[SUA_History2_Date],[SUA_History3_Date],[SUA_History4_Date],[SUA_History5_Date])

Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.

对于此问题,使用 COALESCE 比 ISNULL 或 CASE..WHEN 更好,因为 COALESCE 表达式的输入值可以计算多次。

您还可以使用 NULLIF 检查那些 NULL 值列中的条件。

ISNULL 的 NULL 值转换为 int 数据类型,而对于 COALESCE,您必须提供数据类型。 ISNULL 只接受 2 个参数,而 COALESCE 接受可变数量的参数。