Assuming that I have two tables Historytable and studentInformation table.
What I would like to do is this:
If schoolyear and level exist in Historytable
update studentInformationtable
else
INSERT schoolyear,level to Historytable
update studentInformationtable
My stored procedure code:
ALTER PROCEDURE [dbo].[InsertUpdate]
@studentID INT,
@SchoolYear Nvarchar(20),
@levels Nvarchar(20),
@FirstName Nvarchar(20),
@SurName Nvarchar(20)
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRAN
IF exists (SELECT SchoolYear, Levels
FROM StudentHistory WITH (updlock, serializable)
WHERE StudentID = @studentID)
BEGIN
UPDATE StudentInformation
SET FirstName = @FirstName ,
Surname = @SurName
WHERE StudentID = @studentID
END
ELSE
BEGIN
INSERT INTO Studenthistory (StudentID, SchoolYear, Levels)
VALUES (@studentID, @SchoolYear, @levels)
UPDATE StudentInformation
SET FirstName = @FirstName,
Surname = @SurName
WHERE StudentID = @studentID
END
COMMIT TRAN
END
vb.net code
Using cmd As New SqlClient.SqlCommand("dbo.InsertUpdate", cn)
cmd.Parameters.AddWithValue("@studentID", frmView.dgv1.SelectedCells(0).Value)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@SurName", SqlDbType.VarChar, 100).Value = txtStudLN.Text
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 100).Value = txtStudFN.Text
cmd.Parameters.Add("@SchoolYear", SqlDbType.VarChar, 100).Value = cboSchoolYear.Text
cmd.Parameters.Add("@levels", SqlDbType.VarChar, 100).Value = cboGradeLevel.Text
cmd.ExecuteNonQuery()
MsgBox("Update New record successfully")
End Using
Problem: it does not INSERT a new record in my history table when I insert a new schoolyear and level. Can someone help me to fix my code? Thanks