简体   繁体   English

删除尾随零以及case语句

[英]Remove trailing zeros along with a case statement

I've been trying to remove the trailing zeros from a column of a table. 我一直在尝试从表的列中删除尾随零。 When I use a case statement (to remove the zeros when a flag is turned on, and to keep them when a flag is turned off) it doesn't work properly. 当我使用case语句(在打开标志时删除零,并在关闭标志时保留零)时,它不能正常工作。 It doesn't recognize the flag. 它无法识别该标志。 @Tim Biegeleisen has helped me explain the implicit conversion that was happening though. @Tim Biegeleisen帮助我解释了正在发生的隐式转换。

I want to remove or retain the zeros interchangeably. 我想交替删除或保留零。 When the flag is on for example, I would like 0.091000 be 0.091; 例如,当标记打开时,我希望0.091000为0.091; and when the flag is off, I want it be the same 0.091000. 当标志关闭时,我希望它等于0.091000。 For example, this works properly to retrieve removing the zeros and retaining the zeros separately. 例如,这可以正确地检索除去零并分别保留零。

CREATE TABLE #tablea 
(item CHAR(2), name VARCHAR(10), amount DECIMAL(9,2)) 

INSERT INTO #tablea 
VALUES ('AB', 'D1', 1.10), 
       ('AB', 'D2', 1.00), 
       ('AB', 'D3', 0.90), 
       ('AB', 'D4', 0.09)    

SELECT  CAST(CAST(amount AS DECIMAL(6,2)) AS VARCHAR(max)), cast(CAST(amount 
AS decimal(6,2)) as float)  
FROM #tablea 

It displays two columns: one with the zeros and one without the zeros. 它显示两列:一列为零,一列为零。

However, it doesn't remove the zeros at all in a table. 但是,它根本不会删除表中的零。 It doesn't recognize the flag at all. 它根本不识别该标志。 Here is an example: 这是一个例子:

DECLARE @flag INT = 1

SELECT CASE WHEN @flag = 1 
THEN CAST(CAST(amount AS DECIMAL(6,2)) AS VARCHAR(max))
ELSE amount END 
FROM #tablea 

Can anyone help me with this? 谁能帮我这个?

A CASE expression will always return a value of the same data type, according to the data type precedence rules . 根据数据类型优先规则CASE表达式将始终返回相同数据类型的值。 In your case, considering a branch is returning a varchar and the other one is returning a decimal , the result will always be a decimal . 在您的情况下,考虑到一个分支返回一个varchar ,而另一个分支返回一个decimal ,则结果将始终是一个decimal

To get the desired results, change the CASE expression to return the same data type in both branches: 为了获得所需的结果,请更改CASE表达式以在两个分支中返回相同的数据类型:

DECLARE @flag INT = 1

SELECT CASE WHEN @flag = 1 
THEN CAST(CAST(amount AS DECIMAL(6,2)) AS VARCHAR(100))
ELSE CAST(CAST(amount AS FLOAT) AS VARCHAR(100)) END 
FROM #tablea 

You can do this in this way... 您可以通过这种方式...

    CREATE TABLE #tablea (item CHAR(2), name VARCHAR(10), amount decimal(18,6), flag int) 

    INSERT INTO #tablea 
    VALUES ('AB', 'D1', 1.10, 1), 
           ('AB', 'D2', 1.00, 0), 
           ('AB', 'D3', 0.90, 1), 
           ('AB', 'D4', 0.09, 0)    

    SELECT case when  flag = 1 then FORMAT(amount, 'n2') else FORMAT(amount, 'n4')  end amt FROM #tablea 

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

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