简体   繁体   English

向CASE语句添加文本字符串

[英]Adding text string to CASE Statement

I am using the following SQL CASE: 我正在使用以下SQL CASE:

SELECT 
BomMast.BomStockCode
, BomMast.BomDescription
, CASE
           WHEN StkItem.AveUCst <= 0 THEN 'ERROR' 
           WHEN StkItem.AveUCst > 0 THEN (StkItem.AveUCst * BomComp.ProductionQty) 
        END AS TotalCost
FROM BomComp
INNER JOIN BomMast
ON BomMast.BomID = BomComp.BomMasterKey
INNER JOIN StkItem
ON StkItem.StockLink = BomComp.ComponentStockLink

But I get the following message: 但是我收到以下消息:

Msg 8114, Level 16, State 5, Line 2 Error converting data type varchar to float. 消息8114,级别16,状态5,第2行将数据类型varchar转换为float时出错。

Am I not allowed to add test within the CASE statement? 我是否可以在CASE语句中添加测试?

Thank you! 谢谢!

Change your query to: 将查询更改为:

SELECT BomMast.BomStockCode
    ,BomMast.BomDescription
    ,CASE 
        WHEN StkItem.AveUCst <= 0
            THEN 'ERROR'
        WHEN StkItem.AveUCst > 0
            THEN CAST((StkItem.AveUCst * BomComp.ProductionQty) AS NVARCHAR(MAX))
        END AS TotalCost
FROM BomComp
INNER JOIN BomMast ON BomMast.BomID = BomComp.BomMasterKey
INNER JOIN StkItem ON StkItem.StockLink = BomComp.ComponentStockLink

The datatypes of the values you want to show in either branches of your CASE statements need to be the same in order to work. 要在CASE语句的两个分支中显示的值的数据类型必须相同才能正常工作。

Edit: 编辑:

After @underscore_d 's suggestion, I also consider that it would be a far better option to display NULL instead of the message ERROR and then handle this NULL value in the application level. @underscore_d的建议之后,我还认为,显示NULL而不是消息ERROR ,然后在应用程序级别处理此NULL值将是更好的选择。

Hence, your case statement will change to: 因此,您的案例陈述将更改为:

CASE 
    WHEN StkItem.AveUCst <= 0
        THEN NULL
    WHEN StkItem.AveUCst > 0
        THEN (StkItem.AveUCst * BomComp.ProductionQty)
END AS TotalCost

Your column TotalCost (neither any other column) can be a type-mixture. 您的列TotalCost (任何其他列)都不能是类型混合。 In first case it would be a varchar , in second case it would be float or something like that. 在第一种情况下,它将是varchar ,在第二种情况下,它将是float或类似的东西。 THAT IS NOT POSSIBLE. 这是不可能的。

Yes, text can be used as the result a case statement, as can any datatype, but each case must return the same type, as the results column must have one type only. 是的,文本可以用作case语句的结果,任何数据类型都可以,但是每个case必须返回相同的类型,因为result列必须仅具有一种类型

Your [TotalCost] column has conflicting data types. 您的[TotalCost]列的数据类型冲突。 [StkItem.AveUCst] is a float and the literal value of 'ERROR' is a varchar . [StkItem.AveUCst]浮点型'ERROR'的字面值是varchar If you are intending to retain the benefits of number-based value in your results column, consider replacing 'ERROR' with the SQL keyword NULL . 如果打算在结果列中保留基于数字的值的好处,请考虑使用SQL关键字NULL替换'ERROR'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM