sql server calculate in 'case when'

nononame2021 261 Reputation points
2021-12-13T03:59:39.95+00:00

I can't calculate in case when sql. it always return wrong value

actual_amount= 17.5
expexted_amount=0

select case when cast (cast ([actual_amount] as float) as money) - cast (cast ([expected_amouunt] as float) as money) < 0 then
cast (cast ([actual_amount] as float) as money) - cast (cast ([expected_amouunt] as float) as money)
else '' end as test from table_A;
17.5 -0 ,it is greater than zero, but my sql always return 0 as result

I try to amend sql to the following sql, it is correct, it return '' (blank) as expect, why I can't calculate in the true condition (after then ....)

select case when [actual] - [expected] < 0 then 'yes' else '' end as test from table_A;

how to calculate in case when caluse ?

Developer technologies Transact-SQL
SQL Server Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. LiHong-MSFT 10,056 Reputation points
    2021-12-13T06:20:12.927+00:00

    Hi,@nononame2021
    Welcome to Microsoft T-SQL Q&A Forum!
    Please check this:

    DECLARE @test_table TABLE  
    (  
    ID nvarchar not null,  
    expected_amount nvarchar(25) NULL,  
    actual_amount nvarchar(25) NULL  
    )  
          
    INSERT INTO @test_table VALUES  
     ( 1, 0, 17.5)  
      
    select case when cast (cast ([actual_amount] as float) as money) - cast (cast ([expected_amount] as float) as money) < 0   
           then cast((cast (cast ([actual_amount] as float) as money) - cast (cast ([expected_amount] as float) as money))as nvarchar)  
           else ''  
           end as test from @test_table;  
    

    Output:
    157072-image.png

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Isabellaz-1451 3,616 Reputation points
    2021-12-13T06:20:28.857+00:00

    Hi @nononame2021

    I think there needs to be a varchar() after ‘then’

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.