by steban » Thu Feb 04, 2010 7:32 am
Well, jaymz's snippet was pretty good.
I do a lot of VB .Net with Access and SQL, but I'd say I write pretty basic code that gets the job done, even if not always the prettiest.
Say you want to write a module to insert into one table from another table where a refnum is the same in the other table.
Sub AppendRefNum (ByRef parRefNum as String)
'I tend to dim variables at the top of the sub
Dim conn1 As New ADODB.Connection
Dim strSQLQuery1 as String
Dim strSQLQuery2 as String
Dim rs1 as New ADODB.Recordset
dim strCode as String = ""
dim strDept as String = ""
dim str LastSong as String = ""
'establish connection dsnless in code
conn1.Open_
Provider=Microsoft.Jet." & _
"OLEDB.4.0;" & _
Data Source =C:\AccessDBs\myDB.mdb;" & _
"Jet OLEDB:Engine Type=4"
'write queries in a variable
strSQLQuery1 = "Select * from tblB Where RefNum = " & parRefNum
'how you write the specifics depends on your code, this is just an example - I am inbetween vb6 and .Net in my style.
'the below is .Net requires another sub - might could do Set rs1 = conn1.Execute(strSQLQuery) more vb6 style
OpenRecSet(rs1, conn1, strSQLQuery1)
If rs1.BOF = True and rs1.EOF = True then
'no record
Else
rs1.MoveFirst
strCode = rs1.Fields("Code").Value
strDept = rs1.Fields("Dept").Value
strLastSong = rs1.Fields("Last Song").Value
strvaluestring1 = "(Code, Dept, [Last Song]) Values ('" & strCode & "','" & strDept & "','" & strLastSong & "')"
strvaluestring2 = "Code = '" & strCode & "', Dept = '" & strDept & "', [Last Song] = '" & strLastSong & "'"
strSQLQuery1 = "Select * from tblC Where RefNum = " & parRefNum
OpenRecSet(rs2, conn1, strSQLQuery1)
If rs2.BOF = True and rs2.EOF = True then
'no record so insert into
strSQLQuery2 = "Insert Into tblC & strValueString1 & Where RefNum = " & parRefNum
Else
'exists
so update existing with new data
strSQLQuery2 = "Update tblC Set & strValueString2 & Where RefNum = " & parRefNum
End If
conn1.Execute (strSQLquery2)
End If
End Sub