I see a couple of problems here:
- Your function returns the balance at a specific point in time, not until that point in time. It's not likely that it will return anything at all.
- The function is returning a sum of ALL Ledger Types, not grouped
- The function, temp table and the cursor are unnecessary for the functionality
Have a look at this query:
Select LedgerType,
sum(
case TransactionType
when 'Credit' then amount
when 'Debit' then -amount
end
) Balance,
'',
'',
'',
''
From TRANSACTIONS
Where LedgerName = @LedName
And TransactionDate <= @TransDate
Group By LedgerType
Adjust as necessary.
Eventually use a Between as suggested by Piebald
Also, having an extra field for TransactionType is unnecessary, just make all Debits in the Transaction Table negative.
<Update>
As per your updated question here's an updated query:
CREATE TABLE TRANSACTIONS
(
TransactionDate DateTime,
LedgerNo INT NOT NULL,
LedgerName Varchar(30) NOT NULL,
LedgerType Varchar(30) NOT NULL,
Category Varchar(20) NULL,
Narration Nvarchar(100) NULL,
TransactionType Varchar(12) NOT NULL,
Amount Money NOT NULL,
UserName Varchar(25) NOT NULL
)
;insert into transactions values ('05 Jul 2014',1,'Bank JFK','Bank Account','Assets','Cash Deposit','Credit',10000,'ASD')
;insert into transactions values ('06 Jul 2014',1,'Bank JFK','Bank Account','Assets','Cash Deposit','Credit',3000,'ASD')
;insert into transactions values ('07 Jul 2014',1,'Bank JFK','Bank Account','Assets','Cash Withdrawal','Debit',2500,'ASD')
;insert into transactions values ('07 Jul 2014',2,'AAA Ltd','Sundry Creditors','Liabilities','Goods supply','Credit',5000,'ASD')
;insert into transactions values ('07 Jul 2014',3,'Sun Ltd','Sundry Creditors','Liabilities','Goods supply','Credit',35000,'ASD')
;insert into transactions values ('08 Jul 2014',3,'Sun Ltd','Sundry Creditors','Liabilities','Payment for Goods','Debit',5000,'ASD')
;insert into transactions values ('08 Jul 2014',4,'Sales','Sales Account','Assets','Goods sold','Credit',23000,'ASD')
;insert into transactions values ('09 Jul 2014',4,'Sales','Sales Account','Assets','Cash to bank','Debit',15000,'ASD')
;
Select LedgerType,
sum(
case TransactionType
when 'Credit' then amount
when 'Debit' then -amount
end
) Balance,
category
From TRANSACTIONS
Group By LedgerType,category
Add conditions as necessary, and just wrap it in a stored procedure.
</Update>