1

I've got a fairly large SPROC I'm working on. Well, large as far as I am concerned since I haven't written SQL in quite some time. Anyway, I want to make this Update statement work:

update @salesCommission
set LineAmountWithCashDiscount = (LineAmount - ((LineAmount/ (
   select SUM(LineAmount)
   FROM  @salesCommission
   WHERE InvoiceNumber='00072766')) * CashDiscountAmount))

My problem is that I need to replace the:

WHERE InvoiceNumber='00072766'

clause so that the invoice number is not hard coded. Instead it should just be the invoice number of the current row being updated.

Can anyone show me how to re-write this update query so that it selects the sum of the LineAmount for the current row being updated?

2
  • Is this SQL Server? I assume @salescommission is a table variable? Commented Jan 20, 2011 at 21:46
  • Yes @salescommission is a table variable Commented Jan 20, 2011 at 21:52

2 Answers 2

3
update S
SET LineAmountWithCashDiscount = S.LineAmount - (S.LineAmount / I.Total) * CashDiscountAmount
FROM @salesCommission S
inner join
(
select InvoiceNumber,
    CASE WHEN SUM(LineAmount) = 0 THEN 1 ELSE SUM(LineAmount) END as Total 
from @salesCommission
group by InvoiceNumber
) I on I.InvoiceNumber = S.InvoiceNumber

EDIT: The case to turn "total" into 1 when 0 is to get around #Div/0 errors

Sign up to request clarification or add additional context in comments.

4 Comments

I think this is about it. The SPROC alters ok but I get a divide by zero in this part of it. I think sometimes the total can be zero.
update S SET LineAmountWithCashDiscount = S.LineAmount - (S.LineAmount / I.Total) * CashDiscountAmount FROM @salesCommission S inner join ( select InvoiceNumber, CASE WHEN SUM(LineAmount) = 0 THEN 1 ELSE SUM(LineAmount) END as Total from @salesCommission group by InvoiceNumber ) I on I.InvoiceNumber = S.InvoiceNumber
I modded yours cyberkiwi to the above comment and it seems to work.
@Brent - ah I see. the division by zero problem. answer edited
0

If you're doing this in a stored procedure that's being called by a trigger...

update @salesCommission 
set LineAmountWithCashDiscount = 
(LineAmount - ((LineAmount/ (select SUM(LineAmount) 
FROM  @salesCommission WHERE InvoiceNumber=(Select InvoiceNumber from Inserted)
)) * CashDiscountAmount))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.