Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more: , +
Hi all

Below is my code for inserting data

VB
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()


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...
Posted

1 solution

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.

VB
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()


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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900