How to Create a SQL Stored Procedure who give difference of two columns in a new column for each row
-
Thursday, July 12, 2012 5:34 AM
Hello
I want to create a sql server procedure who subtract two columns and
give its result to the last new added column.Suppose i have two currency fields
in columns as 'bill','payment'.Now i want to calculate it in new column (not existing
in table or view) name balance as balance =balance+(bill-payment) for each row.
OUTPUT LIKE
bill payment balance(new)
400 300 100
500 400 200
700 500 400
here balance work as balance=balance+(bill-payment) for each successive row.
Thanks in Advance for the help :)
With Regards
Rohit Sharma
All Replies
-
Thursday, July 12, 2012 6:07 AMPlease any one reply me regarding this query.
-
Thursday, July 12, 2012 9:13 AM
Create Proc <Store Procedure Name>
as
Begin
Select bill, payment, (bill-payment) as new_balance from <tablename>
End
Please click the Mark as Answer or Vote As Helpful if a post solves your problem or is helpful!
- Marked As Answer by Eileen ZhaoMicrosoft Contingent Staff, Moderator Wednesday, July 18, 2012 3:24 AM
-
Thursday, July 19, 2012 5:40 AM
DECLARE
@bill numeric(10,2) ,DECLARE
@payment numeric(10,2)DECLARE
@balance numeric(10,2)SET
@balance = 0--Say table name tblTransaction
DECLARE
db_cursor CURSOR FOR SELECT bill,payment FROM tblTransactionOPEN
db_cursorFETCH
NEXT FROM db_cursor INTO @bill,@paymentWHILE
@@FETCH_STATUS = 0BEGIN
Set @balance
=@balance+(@bill-@payment)/*
First balance will keep balance of current balance
Second balance will keep the balance amount of previous row
*/
Select @bill
END
,@payment,@balance NEXT FROM db_cursor INTO @bill,@paymentCLOSE
db_cursorDEALLOCATE
db_cursor
Ahsan Kabir
- Edited by Ahsan Kabir Thursday, July 19, 2012 5:41 AM

