Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

how to determine if record was inserted into SQL table

Posted on 2014-12-30
12
Medium Priority
?
188 Views
Last Modified: 2014-12-31
Hi Experts,

I have the following code inserting a record and checking if record was successfully added, however when record already exsists and it would violate a unique index, it giving me an error.
see attached.
strSql = "Insert into Employeestbl(column1,column2..)values(1,2..) ; Select @@Identity"
set rs = CurrentProject.Connection.Execute(strSql).NextRecordset
Debug.Print "New Record ID: ", rs(0)

Open in new window

what is the correct way to handle this?
untitled.bmp
0
Comment
Question by:bfuchs
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 3
  • +1
12 Comments
 
LVL 46

Expert Comment

by:aikimark
ID: 40524971
trap the error and handle it with your code.
You will need an On Error statement
0
 
LVL 4

Author Comment

by:bfuchs
ID: 40524977
Hi,
Is the below correct?
on error resume next
            If UBound(v) > 1 Then
                strSql = "Insert into EmpTovWeeklyHours" _
                & "(SocialSecurity,Day,Hours)" _
                & " Values ('" & Replace(v(0), Chr(32), "") & "','" & Mid(v(3), 3, 2) & "/" & Mid(v(3), 5, 2) & "/" & Mid(v(3), 1, 2) & "'," & Replace(Replace(v(4), Chr(32), ""), "'", "") & ")"
                strSql = strSql & " ; Select @@Identity"
                CurrentProject.Connection.Execute strSql, i
                'Set rs2 = CurrentProject.Connection.Execute(strSql).NextRecordset
                'If rs2(0) = 0 Then
                If err.Number = -2147217873 Then
                    strSql = "Update EmpTovWeeklyHours Set Hours = " & v(4)
                    strSql = strSql & " Where SocialSecurity = '" & v(0) & "'"
                    strSql = strSql & " And Day = '" & Mid(v(3), 3, 2) & "/" & Mid(v(3), 5, 2) & "/" & Mid(v(3), 1, 2) & "'"
                    strSql = strSql & " And Hours <> " & v(4)
                    CurrentProject.Connection.Execute strSql, i
                End If
            End If

Open in new window

0
 
LVL 46

Expert Comment

by:aikimark
ID: 40525004
something like that

There are actually two sets of errors you might need to check
* Err
* Errors(#) -- a collection of errors.  You can access these in a For Each or a traditional For loop
0
 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

 
LVL 85

Assisted Solution

by:Scott McDaniel (Microsoft Access MVP - EE MVE )
Scott McDaniel (Microsoft Access MVP - EE MVE ) earned 600 total points
ID: 40525188
You could also validate prior to running the insert statement, which is (to me) a better idea:

dim rs as New ADODB.Recordset
rs.Open "SELECT COUNT(*) AS RecCount FROM YourTAble WHERE SomeField=SomeVAlue", con

If rs("RecCount") <> 0 Then
  <do your insert here>
End If
0
 
LVL 31

Expert Comment

by:hnasr
ID: 40525974
One way:
Here I use Table1(Field1)
You may include more fields in the insert part of the code.

To insert new records with no duplicates:

If IsNull(DLookup("Field1", "Table1", "Field1='" & "EN" & "'")) Then CurrentDb.Execute "Insert into Table1(Field1) VAlues('EN') "

Open in new window


You may expand to alert of the existence of the record:

If IsNull(DLookup("Field1", "Table1", "Field1='" & "EN" & "'")) Then 
     CurrentDb.Execute "Insert into Table1(Field1) VAlues('EN') "
Else 
     MsgBox("Duplicate record, check data")
End If  

Open in new window

0
 
LVL 4

Author Comment

by:bfuchs
ID: 40526086
Hi Experts,

This will be running in a loop for thousands of records therefore I am looking for the most efficient way to process that, I don't think dlookup is appropriate for this, not sure if opening new recordset is the right approach either, I think the best in this case would be to open one recordset at the beginning and for each record being inserted do rs.findfirst and if rs.nomatch...something like that.

What are your thoughts?
0
 
LVL 31

Assisted Solution

by:hnasr
hnasr earned 600 total points
ID: 40526106
"open one recordset at the beginning and for each record being inserted do rs.findfirst and if rs.nomatch...something like that."

That is fine, but you need to add the record using rs.Add. to be able to reuse rs for further inserts.

You may contribute to the know how by trying all suggestions and tell us the difference.
0
 
LVL 4

Author Comment

by:bfuchs
ID: 40526123
@hnasr,
You meant to say that the same recordset used to verify if the record already exists could be used for inserting in case it does not exists and for updating in case it does? that's cool, I didn't thought of that..
I'm sure that's more efficient than execute insert/update statements thousand times.
0
 
LVL 31

Expert Comment

by:hnasr
ID: 40526142
@bfuchs

I don't claim that because I was referring to reusing the recordset for new insert. You raised another good point to use the recordset for updating existing record. Thanks for the contribution.
0
 
LVL 46

Accepted Solution

by:
aikimark earned 800 total points
ID: 40526154
the two most efficient methods:
1. load the records into an empty table (staging/import) then do joined Insert and then use this new table as the source of an INSERT statement.  The unique index will prevent duplicates.

2. trap the duplicate key errors (as you are now probably doing with the On Error statement) and wrap your insert statements in a transaction (BeginTrans...Commit)
0
 
LVL 4

Author Closing Comment

by:bfuchs
ID: 40526309
Ok Experts, I think I will have plenty of work by now with all those suggestions, at least I got some ideas where to start..
Thank you very Much!
0
 
LVL 31

Expert Comment

by:hnasr
ID: 40526360
Welcome!
0

Featured Post

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Code that checks the QuickBooks schema table for non-updateable fields and then disables those controls on a form so users don't try to update them.
Instead of error trapping or hard-coding for non-updateable fields when using QODBC, let VBA automatically disable them when forms open. This way, users can view but not change the data. Part 1 explained how to use schema tables to do this. Part 2 h…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question