Solved

how to determine if record was inserted into SQL table

Posted on 2014-12-30
12
181 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 3

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
 
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 3

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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure Cloud.

 
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 3

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 3

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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Using Microsoft Access, learn some simple rules for how to construct tables in a relational database. Split up all multi-value fields into single values: Split up fields that belong to other things into separate tables: Make sure that all record…
In Microsoft Access, when working with VBA, learn some techniques for writing readable and easily maintained code.

919 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now