SQL Server 2008R2:评估三列案例语句或合并?

SQL Server 2008R2: Evaluating three columns case statements or coalesce?

这几天我一直在研究如何完成以下任务: 我有一个 table 有备用地址,但我只需要拉城市。然而,城市可能在 field5、field4 或 field3 中。我想做的是用通过评估 <> NULL.

的三个字段找到的值填充另一个名为 city 的字段,但惨遭失败。

这是我目前所知道的,虽然我没有收到任何错误,但出现的唯一值是 field4,因为 field5 为 null 或“”。但如果 field4 也为空,则城市字段为空。出于某种原因,我的查询没有查看 field3,如果有值,则不会填充该值。请帮助!

这是第一次尝试: altcity='Y' 和 (field5 IS null OR field5=' ' ) 的情况 然后 field4 其他 case when altcity='Y' and (field4 IS null OR field4=' ') 然后字段 3 其他字段5 结尾 end as city <- Field5 或 Field4 按原样显示,但如果两个字段均为空,则该字段为空白。看起来好像查询没有查看 field3。

这是第二次尝试:

case when altcity='y' then coalesce(field5,field4,field3) end as city

同样的事情,field5 或 field4 中的值被填充,但 field3 的值没有。

非常感谢您的协助!

有点长手但是当 运行 与您的数据相对应时,以下内容是什么样的:

CASE 
    WHEN altcity='y' THEN   
                        CASE
                            WHEN field5 is not null AND field5 != '' THEN field5
                            WHEN ((field5 is null) OR (field5 = '')) and ((field4 is not null) AND (field4 != ''))  then field4
                            WHEN (((field5 is null) OR (field5 = '')) and ((field4 is null) OR (field4 = ''))) and ((field3 is not null) AND (field3 != '')) then field3
                            ELSE '?'
                        END
    END

看过您的数据示例后,现在可以理解 COALESCE 不起作用,因为它依赖于数据中的 NULL。在 C# 中,有一个字符串函数 IsNullOrEmpty 可以处理这些情况。 T-SQL 没有这个但是有像 this 这样的例子可以帮助创建那个功能并且可以整理 case 语句