如何避免从datagridview到SQL Server表的重复记录插入

问题描述 投票:0回答:1

我在SQL Server 2008 R2中有一个表,其中有一个表CT11。我想要的是停止使用cellendedit事件在表中插入重复记录。因为我得到的记录重复,该怎么办?

Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit

    For Each row In DataGridView1.Rows

        If cmbexam.Text = "CAT 1" Then

            sqlSTR = "INSERT INTO CT11 (Admno, Name, Score) VALUES ('" & row.Cells(0).Value & "','" & row.Cells(1).Value & "','" & row.Cells(2).Value & "')"
            ExecuteSQLQuery(sqlSTR)

        End If

    Next

End Sub
sql-server-2008-r2 vb.net-2010
1个回答
0
投票

首先,学习如何使用SQL命令How to use parameters "@" in an SQL command in VB

如果您希望数据库验证您的输入,请学习如何使用存储过程https://mostafaelmasry.com/2015/10/03/creating-system-stored-procedure-in-sql-server-2008-r2/

在存储过程中添加一个条件,该条件将检查您的输入,例如;

SELECT @record = COUNT(1) FROM CT11 
WHERE Admno = @Admno AND Name = @Name AND Score = @Score;

IF @record = 0
   BEGIN
      INSERT INTO CT11 (Admno, Name, Score) VALUES (@Admno, @Name, @Score);
   END

在VB中

For Each row In DataGridView1.Rows
    If cmbexam.Text = "CAT 1" Then
        MyCommand = New SqlCommand("StoredProcedureName", dbConn)
        MyCommand.CommandType = CommandType.StoredProcedure
        MyCommand.Parameters.AddWithValue("@Admno", row.Cells(0).Value)
        MyCommand.Parameters.AddWithValue("@Name", row.Cells(1).Value)
        MyCommand.Parameters.AddWithValue("@Score", row.Cells(2).Value)
        MyCommand.ExecuteNonQuery()
    End If
Next

或关注此主题:SQL Server stored procedure and execute in VB.NET

或者您可以使用VB通过执行select语句来验证值,并检查是否有记录。

© www.soinside.com 2019 - 2024. All rights reserved.