您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

案例表达式在SQL查询中无法正常工作

案例表达式在SQL查询中无法正常工作

我认为您正在追求这样的事情:

select supplier_name,
       supplier_address,
       supplier_reference,
       contact_number1,
       contact_number2,
       contact_number3,
       case when contact_number2 is not null and contact_number3 is not null then contact_number2||','||contact_number3
            when contact_number3 is null and contact_number2 is null then '0'
            when contact_number2 is null then to_char(contact_number3)
            when contact_number3 is null then to_char(contact_number2)
       end as contact
from   supplier;

请注意,case表达式会在满足第一个条件时停止,因此您应确保条件以正确的顺序排列。(例如,在我的查询中,当您到达“当contact_number2为null时,contact_number3为空”时,由于先前的条件,我们已经知道contact_number3不能为null。)

另外,我已经将您转换CONCAT成更常见(更灵活)的||形式。使用CONCAT,您一次只能连接2个事物,而您可以使用多个||s将各种字符串连接在一起。

出现错误的原因是,将两个数字连接在一起时(尤其是在混合中添加逗号时!),结果将是一个字符串。像您这样的CASE表达式对每个条件的结果使用相同的数据类型。

SQLServer 2022/1/1 18:53:11 有364人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶