Прежде всего, процедура.В SQL вы можете сделать такой расчет с помощью оператора CASE
:
PROC [dbo].[Sp_Ledger_PartyLedgerReport]
@ProfileId INT,
@PartyId INT,
@FromDate DATE,
@ToDate DATE
AS
BEGIN
SELECT Ledger_No,
Ledger_Type,
Ledger_Date,
Credit,
Debit,
Remarks,
--if this is stored as a string (varchar, nvarchar, etc) column,
-- you can REALLY help things by converting this column to a numeric type
CAST(REPLACE(Opening_Balance,',','') AS int) OpeningBalance,
CASE WHEN ClosingBalance = 0
THEN OpeningBalance - Credit + Debit
ELSE ClosingBalance - Credit + Debit
END ClosingBalance
Party_Id,
Party_Name,
Profile_Address,
Profile_Contact,
Profile_FullName
FROM tblLedger
JOIN tblCustomer A ON a.Party_Id = CustomerId
JOIN tblProfile ON Profile_Id = A.ProfileId
WHERE Ledger_Date BETWEEN @FromDate AND @ToDate
AND Profile_Id = @ProfileId
AND Party_Id = @PartyId
ORDER BY Ledger_Date ASC
END
Но я боюсь, вам нужно, чтобы это действовало как промежуточный итог, а это немного сложнее. Или, возможно, поле ClosingBalance
настолько простое, но вы также хотите обрабатывать текущие вычисления на сервере, а не в C #.В любом случае, ссылка может помочь вам.Функции управления окнами - ваш друг:)
Мы также можем внести некоторые улучшения в C #:
using(SqlCommand cmd = new SqlCommand("Sp_Ledger_PartyLedgerReport", con))
{
cmd.CommandType = CommandType.StoredProcedure;
// use EXPLICIT types here that match your database columns. Trust me.
cmd.Parameters.Add("@ProfileId", SqlDbType.Int).Value = profileID;
cmd.Parameters.Add("@PartyId", SqlDbType.Int).Value = partyID;
cmd.Parameters.Add("@FromDate", SqlDbType.DateTime).Value = fromDate;
cmd.Parameters.Add("@ToDate", SqlDbType.DateTime).Value = toDate;
//if you're just gonna convert to a List right away, DataAdapter/DataTable have extra overhead
con.Open();
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
//reduce boilerplate & indentation with DataReader and type initializer
var l = new Ledger() {
LedgerNo = (string)rdr["Ledger_No"],
ProfileFullName = (string)rdr["Profile_FullName"],
ProfileAddress = (string)rdr["Profile_Address"],
ProfileContact = (string)rdr["Profile_Contact"],
CustomerId = (int)rdr["Party_Id"],
CustomerName = (string)rdr["Party_Name"],
LedgerType = (string)rdr["Ledger_Type"],
//Do you *really* need ToString() and Parse() calls here?
//they have surprisingly high performance costs, and
// you get by just fine without them on other columns.
LedgerDate = DateTime.Parse(rdr["Ledger_Date"].ToString()),
Remarks = (string)rdr["Remarks"],
OpeningBalance = (int)rdr["OpeningBalance"],
TotalCredit = (int)rdr["Credit"],
TotalDebit = (int)rdr["Debit"],
};
int cb = (int)rdr["ClosingBalance"];
l.Balance = (cb == 0) ?
l.OpeningBalance - l.TotalCredit + l.TotalDebit :
cb - l.TotalCredit + l.TotalDebit;
myList.Add(l);
}
}
}