views:

108

answers:

3

I'm trying to perform calculations in T-SQL, but am having some problems with it. Here is what I'm trying to do:

DECLARE @CNT money
SELECT @CNT = 0

Select Amount,
        case
            when Service like 'pay_in' then SET @CNT = @CNT + Amount
            when Service like 'pay_out' then SET @CNT= @CNT - Amount
        end
   from Payment where isActive = 1

select @CNT

Due to my poor knowledge of T-SQL syntax I'm stuck here, and would be very thankful if someone can push me in the right direction. Thank you!

+4  A: 

You can simplify it further without using variables:

Select Sum(Case Service
           When 'pay_in' Then Amount
           When 'pay_out' Then -Amount
           End) as Total
From Payment 
Where isActive = 1
Nick Craver
+1  A: 

There's no need for a SET inside a SELECT. Try:

set @CNT = 0

select 
   @CNT = case
        when Service like 'pay_in' then @CNT + Amount
        when Service like 'pay_out' then @CNT - Amount
    end
from Payment 
where isActive = 1

Or, without a variable:

 Select 
    sum(case
        when Service like 'pay_in' then Amount
        when Service like 'pay_out' then -Amount
    end) as Total
 from Payment 
 where isActive = 1
Andomar
Have you actually tried your first suggestion before posting?
Frank Kalis
@Frank Kalis: No, I didn't try it. On rereading it you can't select amount and assign to @cnt in the same query, and you should initialize @cnt.
Andomar
Frank Kalis
+5  A: 

SQL works best with set-based approaches. Try not to solve problems by iterating your data set, but rather by aggregating it.

DECLARE @CNT money

SELECT 
  @CNT = SUM(
    CASE Service 
      WHEN 'pay_in'  THEN Amount
      WHEN 'pay_out' THEN -1 * Amount
      ELSE 0
    END
  )
FROM
  Payment 
WHERE
  isActive = 1

SELECT @CNT
Tomalak