Solved

how to determine if record was inserted into SQL table

Posted on 2014-12-30
12
182 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
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
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

Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

Question has a verified solution.

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

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Phishing attempts can come in all forms, shapes and sizes. No matter how familiar you think you are with them, always remember to take extra precaution when opening an email with attachments or links.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

770 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