防止从复选框列表VB.NET插入重复数据

时间:2019-02-08 02:36:59

标签: vb.net foreach checkboxlist

问候!

我的网络表单中有复选框列表项。它已经可以正常工作,但是我想防止它向表中插入相同数据(重复)。
这是我的代码:

Using conn2 As New SqlConnection()
        conn2.ConnectionString = ConfigurationManager _
            .ConnectionStrings("BackboneConnectionString").ConnectionString()
        Using cmd As New SqlCommand
            cmd.CommandText = "Insert into EL_MstFunctionalNilai values(@IDFunc, @nik, @IDFuncParent, @IDFuncChild, @IDFuncMtr, '', '', '0')"
            cmd.Connection = conn2
            conn2.Open()
            For Each item As ListItem In CheckBoxList2.Items
                If item.Selected Then

                    Dim urutan As Int32 = GetNumberFunctional()
                    Dim str As String = item.Value.ToString

                    Dim strArr() As String = str.Split("_")
                    Dim IDFunctionalParent1 As String = strArr(0)
                    Dim IDFunctionalChild1 As String = strArr(1)
                    Dim IDFunctionalMtr1 As String = strArr(2)

                    cmd.Parameters.Clear()
                    cmd.Parameters.AddWithValue("@IDFunc", urutan)
                    cmd.Parameters.AddWithValue("@nik", txtnik.Text)
                    cmd.Parameters.AddWithValue("@IDFuncMtr", IDFunctionalMtr1) 'mtr
                    cmd.Parameters.AddWithValue("@IDFuncParent", IDFunctionalParent1) 'parent 
                    cmd.Parameters.AddWithValue("@IDFuncChild", IDFunctionalChild1) 'child

                    cmd.ExecuteNonQuery()

                End If
            Next
            conn2.Close()
        End Using
    End Using

NB。 “ nik”是员工ID->因此1名员工不会得到重复的数据

如何检查表中是否存在“ IDFunctionalParent1”和“ IDFunctionalChild1”和“ IDFunctionalMtr1”(参数:“ nik” ),然后再将它们插入表格?

欢呼

1 个答案:

答案 0 :(得分:0)

在您的插入语句中使用此

coalesce((select max(id)+1 from table),0)

如果我把它放在您的代码上,那么

Insert into EL_MstFunctionalNilai values(coalesce((select max(id)+1 from EL_MstFunctionalNilai),0), @nik, @IDFuncParent, @IDFuncChild, @IDFuncMtr, '', '', '0')
如果返回null,

0是默认值