2009-09-07 47 views
1

我正在使用VB.NET和下面的代碼按鈕單擊事件。如何停止在表中使用vb.net插入相同的記錄

Protected Sub ibtnSendInvites_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ibtnSendInvites.Click 
     Try 
      Dim emailList As New List(Of String) 
      Dim conString As String = WebConfigurationManager.ConnectionStrings("LocalSqlServer").ConnectionString 
      Dim con As New SqlConnection(conString) 
      con.Open() 
      Dim cmd As SqlCommand 
      For Each curRow As GridViewRow In GridView1.Rows 
       Dim chkSelect As CheckBox = CType(curRow.Cells(1).FindControl("chkSelect"), CheckBox) 
       Dim emailLabel As Label = CType(curRow.Cells(1).FindControl("lblEmailAddress"), Label) 
       If chkSelect.Checked Then 
        emailList.Add(emailLabel.Text) 
        cmd = New SqlCommand("uspInsertDelegate", con) 
        cmd.CommandType = CommandType.StoredProcedure 
        cmd.Parameters.Add("@CourseID", SqlDbType.Int).Value = Session("CourseID") 
        cmd.Parameters.Add("@CPUserID", SqlDbType.Int).Value = CType(curRow.Cells(1).FindControl("lblCPUserID"), Label).Text 
        cmd.Parameters.Add("@StatusID", SqlDbType.Int).Value = 25 
        cmd.Parameters.Add("@CreateUser", SqlDbType.VarChar).Value = Session("LoggedInUser") 
        cmd.ExecuteNonQuery() 
       End If 
      Next 
      For Each email As String In emailList 
       Dim message As String = "Please confirm your booking " 
       Dim subject As String = "UserPoint Course Booking Invitation Email" 
       Dim from As String = "[email protected]" 
       SendEmail.SendMessage(subject, message, from, email, "") 
      Next 
     Catch ex As Exception 

     End Try 
    End Sub 

我想,如果用戶試圖插入具有相同的記錄相同CourseIDCPUserID拋出異常。

+0

檢查這個問題:[停止插入表中,如果記錄已經存在](http://stackoverflow.com/questions/1388235/stop-inserting-in-table-if-record-already-exists) – Shoban 2009-09-07 08:48:40

回答

2

Put a unique index在DATABASE表在這兩列上。如果您嘗試插入重複項,則會返回異常。

CREATE UNIQUE INDEX IDX_Course_UserId_Delegate 
    ON Delegate (CourseID,CPUserID) 

或改變SP來檢查第一

或添加一個INSERT觸發器上,這將提高和異常的DB。

你抓

Throw New Exception("CANNOT INSERT DUPLICATE TROW", ex) 
+0

謝謝!我可以使用我的上面的代碼的示例代碼? – 2009-09-07 08:45:42

+0

親愛的,但我可以有不同的cpuserid許多課程ID反之亦然 – 2009-09-07 08:48:04

+0

那就好了。以上只是意味着只允許具有兩個值的唯一行,允許其他任何排列。 – 2009-09-07 08:50:04

0

兩個選項真的 - 查詢表首先看是否行存在並引發自定義異常(包裝在一個事務整個事情),或在執行本具有唯一約束/索引的數據庫(無論如何你都應該這樣做)。然後當你嘗試數據庫時,數據庫會提出一個錯誤...

+0

謝謝!,我可以使用我的上面的示例代碼碼? – 2009-09-07 08:45:00

+0

致謝親愛的您的幫助! – 2009-09-07 09:32:17

1

而不是讓它引發異常,你可以改變你的存儲過程「uspInsertDelegate」來檢查該行是否已經存在,然後再嘗試插入,並報告它是否做到了。

如Preet所說,我也會在數據庫中創建唯一的索引,只是爲了安全起見。

+0

我在列上創建了唯一索引,以及在我的過程中使用IF NOT EXISTS(SELECT * FROM tblDelegate WHERE CourseID = @CourseID和CPUserID = @CPUserID)在插入之前創建了唯一索引,現在應如何顯示消息給用戶的記錄不能被插入,因爲它已經存在於表格中 – 2009-09-07 08:59:25