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
Solved

how to determine if record was inserted into SQL table

Posted on 2014-12-30
12
183 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
  • 4
  • 4
  • 3
  • +1
12 Comments
 
LVL 45

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 45

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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 84

Assisted Solution

by:Scott McDaniel (Microsoft Access MVP - EE MVE )
Scott McDaniel (Microsoft Access MVP - EE MVE ) earned 150 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 30

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 30

Assisted Solution

by:hnasr
hnasr earned 150 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 30

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 45

Accepted Solution

by:
aikimark earned 200 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 30

Expert Comment

by:hnasr
ID: 40526360
Welcome!
0

Featured Post

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

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

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Learn how to number pages in an Access report over each group. Activate two pass printing by referencing the pages property: Add code to the Page Footers OnFormat event to capture the pages as there occur for each group. Use the pages property to …
In Microsoft Access, learn different ways of passing a string value within a string argument. Also learn what a “Type Mis-match” error is about.

790 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