sql - "CASE" in SQL Query not work with string values
问题描述
I have Simple “Case” query that work with number but not work with string?
It Work Correctly:
SELECT
OrderItem_ID,Cost,
Case
When Cost = 0 then 555
Else Cost
End As CostStatus
FROM
OrderItem
It Doesn’t work:
SELECT
OrderItem_ID,Cost,
Case
When Cost = 0 then "Free"
Else Cost
End As CostStatus
FROM
OrderItem
Error is: Invalid column name 'Free'.
解决方案
All the results from a CASE expression should return the same data type or need to be implicitly converted following data precedence. In this case, numeric types have a higher precedence than string data types. Therefore, you need to use an explicit conversion.
SELECT
OrderItem_ID,Cost,
Case
When Cost = 0 then 'Free'
Else CAST( Cost AS varchar(13))
End As CostStatus
FROM
OrderItem
EDIT: I changed the double quotes to single quotes which are the standard in T-SQL. Double quotes will only work if QUOTED_IDENTIFIERS is OFF. Both problems were present in the query presented.
推荐阅读
- computer-science - 使用固定状态下推自动机
- node.js - 如何通过Postman使用nodejs restAPI计算两个数字的基本和
- eclipse - 在 ESF 模拟器中运行 Hello_Osgi 在 Eclipse EE、Kura、Ubuntu Linux 上崩溃
- firebase - 'package:flutter/src/widget/text.dart':断言失败:第 378 行 pos 10;'data != null':必须向 Text 小部件提供非空字符串
- swift5 - 读取数据时 FileHandler 出现问题
- vue.js - 如何解决 ionic-vue 中的 CROSS Origin 问题?
- mysql - Laravel8 不会对迁移创建外键约束
- gitlab - 通过 API 创建标签或发布时如何防止触发 CI/CD
- here-api - Here API:按距离和按时间等值线之间的缓冲区差异
- java - 从每页itext 7 java的第一段中删除前导