如何使用vb.net和SQL Server检查记录是否存在

时间:2016-04-10 05:43:11

标签: sql-server vb.net sql-server-2008-r2

假设我有两个表HistorytablestudentInformation table

我想做的是:

If schoolyear and level exist in Historytable
    update studentInformationtable
else
   INSERT schoolyear,level to Historytable
    update studentInformationtable

我的存储过程代码:

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代码

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

问题:当我插入新的INSERTschoolyear时,我的历史记录表中没有level新记录。有人可以帮我修改我的代码吗?感谢

1 个答案:

答案 0 :(得分:1)

请改为尝试:

ALTER PROCEDURE [dbo].[InsertUpdate] 
    -- Add the parameters for the stored procedure here

@studentID INT, 
@SchoolYear Nvarchar(20),
@levels Nvarchar(20),
@FirstName Nvarchar(20),
@SurName Nvarchar(20)


AS
BEGIN

    SET NOCOUNT ON;

BEGIN TRAN

   UPDATE StudentInformation
   SET FirstName = @FirstName ,
   Surname = @SurName
   WHERE StudentID = @studentID

   INSERT INTO Studenthistory (StudentID,SchoolYear, Levels)
   SELECT @studentID,@SchoolYear,@levels
   WHERE NOT EXISTS(
        SELECT 1
        FROM Studenthistory
        WHERE StudentID = @studentID
   )


COMMIT TRAN
END

注意:

  1. 无需在if和else部分中编写update语句。
  2. 只有select语句将返回记录时,insert语句才会向Studenthistory添加新记录。 where子句中的条件确保每个学生只有一条记录将被插入历史表中。
  3. 但是,对于每个学生只保留一个历史记录,我没有多大意义。我想你的意思是你要保留学年的先前价值和每个学生的水平。如果是这样,exists内的查询应为:

    SELECT 1
    FROM Studenthistory
    WHERE StudentID = @studentID
    AND SchoolYear = @SchoolYear,
    AND Levels = @levels