Solved

how to determine if record was inserted into SQL table

Posted on 2014-12-30
12
180 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
Comment Utility
trap the error and handle it with your code.
You will need an On Error statement
0
 
LVL 3

Author Comment

by:bfuchs
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 30

Assisted Solution

by:hnasr
hnasr earned 150 total points
Comment Utility
"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
Comment Utility
@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
Comment Utility
@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
Comment Utility
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
Comment Utility
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
Comment Utility
Welcome!
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
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.
Viewers will learn how the fundamental information of how to create a table.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

744 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

14 Experts available now in Live!

Get 1:1 Help Now