如何在使用SQL插入之前检查重复值

时间:2014-04-10 20:50:47

标签: sql vb.net insert duplicates

我创建了一个INSERT SQL查询,工作正常......直到我尝试发送重复值。我很高兴数据库停止重复值,但我不希望系统崩溃。我想知道如何检查我想要输入的值是否已经在数据库中。如果是,请清除该框并生成一个消息框。如果不是,请继续执行INSERT命令 这是我的代码:

Dim strPersonID As String = cboPersonID.Text If strPersonID = "" Then Exit Sub 'Declares contents of text boxes as a string so it can be used in the 'SQL string Dim strForename As String = txtForename.Text Dim strSurname As String = txtSurname.Text Dim strDateOfBirth As String = txtDateOfBirth.Text Dim strCurrentlyWith As String = CheckIfWith() Dim strConditions As String = txtConditions.Text 'Add new record to table Dim strSQL As String = "INSERT INTO tblDetail VALUES('" & strPersonID _ & "','" & strForename & "','" & strSurname & "','" & strDateOfBirth & "'," & strCurrentlyWith & ",'" & strConditions & "')" Dim CM As New OleDbCommand(strSQL, CN)

2 个答案:

答案 0 :(得分:0)

您可以随时捕获异常,然后根据该消息弹出消息。更复杂的替代方法是启动事务,运行select查询以检查重复,然后如果没有重复,则运行insert语句,然后提交事务。如果存在重复项,您可以提交事务并通知用户。

以下是关于如何使用try-catch块执行此操作的粗略概念:

        Try
            'put your code here that could throw the exception.
        Catch ex As SqlClient.SqlException
            If (ex.Message.Contains("whatever the message is stating you have a duplicate")) Then
                MsgBox("You have a duplicate!")
            End If
        End Try

答案 1 :(得分:0)

将您的插入内容置于If not Exists语句

Dim strSQL As String = "If Not Exists (" & _
             "Select * From tblDetail "  & _
             "Where PersonId = " & strPersonID & ")" & _
    "INSERT INTO tblDetail VALUES('" & strPersonID _   
         & "','" & strForename & "','" & strSurname & 
         "','" & strDateOfBirth & "'," &
          strCurrentlyWith & ",'" & strConditions & "')"