• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 168
  • Last Modified:

create new records using adodb and sql

Another newbie question.
I am using ADODB.Connection and ADODB.Recordset withMicrosoft SQL
Lets say I have two tables, one company and one employee and they are related.
What call do I make to ADODB to create a new record in the two tables. How does the primary key get placed into the foreign key of the child table?


Dim comp as string
Dim emp as string
Comp = “Albertsons”
Emp = “shayne”

Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
 Set cn = New ADODB.Connection
 set rs = New ADODB.Recordset
cn.Open '"Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=test;Data Source=DURGA"

cn.Open


now I do not know what to do

Thanks in advance
shayne
0
shayne23d
Asked:
shayne23d
1 Solution
 
pique_techCommented:
You should be able to use ADO to add the record to the "main" table, get its PK value, then immediately add the record to the "child" table using the PK from the "main" record.  Broadly,

Dim rs1 As ADODB.Recordset: Set rs1 = New ADODB.Recordset
Dim rs2 As ADODB.Recordset: Set rs1 = New ADODB.Recordset
Dim GetKey As Long
rs1.Open "MainTableName", cn, adOpenDynamic, adLockOptimistic, adCmdTable
rs2.Open "MainChildName", cn, adOpenDynamic, adLockOptimistic, adCmdTable

rs1.AddNew
    rs1("Field1Name") = "blah"
    ...
rs1.Update
GetKey = rs1("PrimaryKeyFieldName")

rs2.AddNew
    rs2("ForeignKey") = GetKey
    ...
rs2.Update
...
'Cleanup
rs1.Close
rs2.Close
Set rs1 = Nothing
Set rs2 = Nothing

This should work because after calling the recordset's Update method, the new record becomes the current record (docmumented here:  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmthaddnew.asp)


0
 
shayne23dAuthor Commented:
yeah! I was going to use a function to return the primary key of the record in sql, this is what I was looking for.
Thank you
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now