I got this problem that I got when I insert value of a list into the database.
At first, it works perfectly, but when being run a second time, it shows the error. I knew that many of this error has been solved in here.
But for my condition it happened at the second entry where the first one works perfectly.
This is the stored procedure:
ALTER PROCEDURE [dbo].[InsertMonthlyIncome]
@UserId INT,
@MonthlyIncomeName VARCHAR(300),
@MonthlyIncomeAmount FLOAT,
@TotalMonthlyIncome FLOAT,
@Month VARCHAR(30),
@Year INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @InfoId INT,
@InfoTotalIncome FLOAT, @InfoTotalExpense FLOAT,
@InfoMonth VARCHAR(30), @InfoYear INT, @InfoUserId INT
SELECT
@InfoId = MFInfoId, @InfoTotalIncome = MFInfoTotalIncome,
@InfoTotalExpense = MFInfoTotalExpense,
@InfoMonth = MFInfoMonth, @InfoYear = MFInfoYear,
@InfoUserId = MFUserId
FROM
MonthlyFinancialInformation
WHERE
MFInfoMonth = @Month
AND MFInfoYear = @Year
AND MFUserId = @UserId
IF @InfoId IS NOT NULL
BEGIN
UPDATE MonthlyFinancialInformation
SET MFInfoTotalIncome = (@TotalMonthlyIncome + MFInfoTotalIncome)
WHERE MFInfoId = @InfoId
END
ELSE
BEGIN
INSERT INTO MonthlyFinancialInformation(MFInfoTotalIncome, MFInfoMonth, MFInfoYear, MFUserId)
VALUES (@TotalMonthlyIncome, @Month, @Year, @UserId)
END
INSERT INTO MonthlyCertainIncome(MCIncomeName, MCIncomeAmount, MCIncomeDateCreated, MCUserId)
VALUES (@MonthlyIncomeName, @MonthlyIncomeAmount, GETDATE(), @UserId)
END
Then this is the C# code:
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["UangBulananComConnectionString"].ConnectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("InsertMonthlyIncome", con))
{
foreach (var income in monthlyIncomeList)
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@UserId", userId);
cmd.Parameters.AddWithValue("@MonthlyIncomeName", income.MonthIncomeName);
cmd.Parameters.AddWithValue("@MonthlyIncomeAmount", income.MonthIncomeAmount);
cmd.Parameters.AddWithValue("@TotalMonthlyIncome", income.MonthIncomeAmount);
cmd.Parameters.AddWithValue("@Month", insertMonth);
cmd.Parameters.AddWithValue("@Year", insertYear);
cmd.ExecuteNonQuery();
}
con.Close();
monthlyIncomeList.Clear();
}
}
Thanks for any help.