检查是否存在然后插入更新

时间:2016-12-12 08:43:55

标签: mysql sql sql-server vb.net

如果数据不存在,我需要检查数据是否存在然后我将能够插入和更新但是如果数据存在,则消息框将显示数据已经存在但是当我尝试添加相同的数据时它已经存在,它仍然会添加,并且没有消息框显示它已经存在。

这是我的代码

  If jobtitle <> "" And businessunit <> "Please Select" And division <> "Please Select" And subdivision <> "Please Select" And classification <> "Please Select" And subclassification <> "Please Select" Then
            insrtResult = UpdateInsDelRecord("UPDATE EMP_MASTERTBL SET JOBTITLE = '" & jobtitle & "' " & _
                                   "WHERE MASTERID = '" & empID & "'" & _
                                   ";" & _
                                   "INSERT INTO EMPGROUP_TBL(MASTERID, BUSINESS_UNIT, " & _
                                   "DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
                                   "('" & HandleQuote(empID) & "', " & _
                                   "'" & businessunit & "' ," & _
                                   "'" & division & "' ," & _
                                   "'" & subdivision & "' ," & _
                                   "'" & classification & "' ," & _
                                   "'" & subclassification & "')")

            If Not insrtResult Then
                MessageBox("alert('Error Ocurred While Inserting a Data.')")
            Else
                MessageBox("alert('Successfully Added.')")
            End If
        Else
            MessageBox("alert('Data Already Exist.')")
        End If

我的代码可能出现什么问题?提前谢谢。

1 个答案:

答案 0 :(得分:0)

对于SQL Server检查MERGE查询,我使用它在我自己的数据库上执行“upsert”,它似乎也表现得足够快。

您可以选择条件并执行不同的操作,无论它返回true还是false(例如,如果ID已存在,则更新,否则插入)

对于MySql,我认为有更容易编写的解决方案,不幸的是我现在记不清了

https://msdn.microsoft.com/en-us/library/bb510625.aspx

相关问题