如何检查记录是否已存在 [英] How to check record already exists or not

查看:61
本文介绍了如何检查记录是否已存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好



以下是我输入数据的代码



Hi all

Below is my code for inserting data

Dim cmd As New SqlCommand("insert into UnitOfMeasurement values('" & txtUnitType.Text & "','" & txtDecimalValue.Text & "','" & a & "','" & txtPresizecut.Text & "')", con)
          con.Open()
          Dim answer As String = MsgBox("Are you sure ???", MsgBoxStyle.YesNoCancel + MsgBoxStyle.Question)
          If answer = vbYes Then
              cmd.ExecuteNonQuery()
              MsgBox("Inserted..", MsgBoxStyle.Information)
          End If
          con.Close()





现在我想在插入之前检查具有相同名称的UnitType是否存在于数据库中或者不是..如果是,它将给出错误,否则它将插入。 (即检查重复的UnitType)



请告诉我怎么做...



Now i want to check before inserting that UnitType with same name is present in database or not..if yes the it will give error else it will insert.(i.e. Checking for duplicate UnitType)

Please tell me how to do this...

推荐答案

取决于实际要求你实际上有几种选择。



第一种方法是使用IF Exists ... ELSE ...方法基于SQL方法工作您可以在这里找到详细信息:



sql-if-exists-update-else-insert [ ^ ]



另一种方法是在insert命令之前运行一个查询,如果它存在,则返回项目索引。



Depending on your actual requirement you actually have several options.

The first is to work based on an SQL approach by using the "IF Exists ... ELSE ..." approach which you can find details of here:

sql-if-exists-update-else-insert[^]

An alternative would be to run a query prior to your insert command that returns in index of an item if it exists.

Dim cmd As New SqlCommand("Select id from UnitOfMeasurement where unittype='" & txtUnitType.Text & "'", con)
          con.Open()
          dim response as int =   cmd.ExecuteScalar()
             IF response > 0 Then 'Raise message box to say entry already exists 
             End IF
          con.Close()





此处的代码不是100%,因为我不知道您的列名等,所以它需要一些调整,但旨在给你一个想法。



The code here is not 100% as I don't know your column names etc, so it will need a bit of tweaking but is designed to give you an idea.


这篇关于如何检查记录是否已存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆