I am really struggling here. I am building up a query inside VBA to link to several tables inside Oracle and inside Access. I need to make sure what I have uploaded to Oracle Matches what is in the Access DB.
I have:
SourceField1 (Always populated)
SourceField2 (Sometimes populated)
If source field 2 is blank I want to ignore it and not join to it. The best way I have done this is try with an Nz and replace with SourceField1.
strSQL = "INSERT INTO ERROR_TABLE (ORACLE_FIELD, TRANSFORM_FIELD) SELECT " & MatchValues!ORACLE_TABLE_NAME & "." & MatchValues!FieldName & ", " & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!FieldName
strSQL = strSQL & " FROM " & MatchValues!TRANSFORM_TABLE_NAME & " INNER JOIN " & MatchValues!xfTableName
strSQL = strSQL & " ON " & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!SourceField1 & " = " & MatchValues!xfTableName & "." & MatchValues!ReferenceField1 & ""
strSQL = strSQL & " AND " & MatchValues!TRANSFORM_TABLE_NAME & ".Nz(" & MatchValues!SourceField2 & "," & MatchValues!SourceField1 & ") = " & MatchValues!xfTableName & ".Nz(" & MatchValues!ReferenceField2 & "," & MatchValues!ReferenceField1 & ")"
strSQL = strSQL & " INNER JOIN " & MatchValues!ORACLE_TABLE_NAME & " ON (" & MatchValues!xfTableName
strSQL = strSQL & ".KEYVAL = " & MatchValues!ORACLE_TABLE_NAME & ".KEYVAL)"
strSQL = strSQL & " WHERE (" & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!FieldName
strSQL = strSQL & " <> " & MatchValues!ORACLE_TABLE_NAME & "." & MatchValues!FieldName & ")"
Which gives me this:
INSERT INTO ERROR_TABLE (ORACLE_FIELD, TRANSFORM_FIELD) SELECT UNI73MART1_DCappl.DECSN, tbluniDCappl.DECSN FROM tbluniDCappl INNER JOIN XF_DC_ref ON tbluniDCappl.REFVAL = XF_DC_ref.REFVAL AND tbluniDCappl.Nz(,REFVAL) = XF_DC_ref.Nz(,REFVAL) INNER JOIN UNI73MART1_DCappl ON (XF_DC_ref.KEYVAL = UNI73MART1_DCappl.KEYVAL) WHERE (tbluniDCappl.DECSN <> UNI73MART1_DCappl.DECSN)
Try this with proper concatenation of the Nz expressions:
strSQL = "INSERT INTO ERROR_TABLE (ORACLE_FIELD, TRANSFORM_FIELD) SELECT " & MatchValues!ORACLE_TABLE_NAME & "." & MatchValues!FieldName & ", " & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!FieldName
strSQL = strSQL & " FROM " & MatchValues!TRANSFORM_TABLE_NAME & " INNER JOIN " & MatchValues!xfTableName
strSQL = strSQL & " ON " & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!SourceField1 & " = " & MatchValues!xfTableName & "." & MatchValues!ReferenceField1 & ""
strSQL = strSQL & " AND " & MatchValues!TRANSFORM_TABLE_NAME & "." & Nz(MatchValues!SourceField2, MatchValues!SourceField1) & " = " & MatchValues!xfTableName & "." & Nz(MatchValues!ReferenceField2, MatchValues!ReferenceField1) & ")"
strSQL = strSQL & " INNER JOIN " & MatchValues!ORACLE_TABLE_NAME & " ON (" & MatchValues!xfTableName
strSQL = strSQL & ".KEYVAL = " & MatchValues!ORACLE_TABLE_NAME & ".KEYVAL)"
strSQL = strSQL & " WHERE (" & MatchValues!TRANSFORM_TABLE_NAME & "." & MatchValues!FieldName
strSQL = strSQL & " <> " & MatchValues!ORACLE_TABLE_NAME & "." & MatchValues!FieldName & ")"
Pull the call to Nz out of the SQL. The two fields in question exist in the VBA context and so should be checked within the VBA code, not embedded in the SQL string.
strSQL = strSQL & " AND " & MatchValues!TRANSFORM_TABLE_NAME & "." Nz( MatchValues!SourceField2 , MatchValues!SourceField1) & " = " & MatchValues!xfTableName & "." & Nz( MatchValues!ReferenceField2 , MatchValues!ReferenceField1)
When NULL is concatenated with a string using &, null is just converted to a blank string. So the expression ".Nz(" & MatchValues!SourceField2 & "," & MatchValues!SourceField1 & ") = " & MatchValues!xfTableName & ".Nz(" & MatchValues!ReferenceField2 & "," & MatchValues!ReferenceField1 & ")" would simply produce the string value ".Nz(, SourceField1Name) = tablename.Nz(,ReferenceField1Name)... which is bad SQL syntax. I think Nathan_Sav was trying to point this out, but not very clear about it.
Hint 1: You should always debug an SQL statement built in code by printing out the actual SQL statement. You should have included that in your question.
Hint 2: Try using the VBA line continuation character _
Related
I've been to dozens of sites. None address my particular question. All (including official Microsoft) tell me to do what I'm doing.
Dim strSQL As String
strSQL = """INSERT INTO tblVolunteers " & vbCrLf & _
"VALUES (" & [txtTitle] & "," & [txtFirstName] & "," & [txtMiddle] & "," & [txtLastName] & "," & [txtEmail] & _
"," & [txtPhone] & "," & [txtChurch] & "," & [txtGroup] & "," & [txtCouncil] & "," & [chkParCo] & "," & _
[txtMailAdd] & ");"""
CurrentDb.Execute strSQL
Here's what Microsoft has to say:
Run-time error '3078'
The Microsoft Access database engine cannot find the input table or query ""INSERT INTO tblVolunteers
VALUES (Mr.,John,L.,Smith,jlsmith#email.com,800-555-1212,St. Smith's,Smith,1234,-1,10 Smith St.
Smithville, TX 77777-3333);"". Make sure it exists and that its name is spelled correctly.
Why is it looking for a table or query when not only have I specified VALUES but it has picked up all the values from the form?
You could either use my function CSql and concatenate the values like this:
strSQL = "INSERT INTO tblVolunteers " & _
"VALUES (" & CSql([txtTitle]) & "," & CSql([txtFirstName]) & "," & CSql([txtMiddle]) & "," & _
CSql([txtLastName]) & "," & CSql([txtEmail]) & "," & CSql([txtPhone]) & "," & CSql([txtChurch] & "," & _
CSql([txtGroup]) & "," & CSql([txtCouncil]) & "," & CSql([chkParCo]) & "," & CSql([txtMailAdd]) & ");"
or you could skip this mess and use DAO for much cleaner coding and easier debugging:
Dim Records As DAO.Recordset
Dim Sql As String
Sql = "Select * From tblVolunteers"
Set Records = CurrentDb.OpenRecordset(Sql, dbOpenDynaset, dbAppendOnly)
Records.AddNew
Records!Title.Value = Me!txtTitle.Value
Records!FirstName.Value = Me!txtFirstName.Value
Records!Middle.Value = Me!txtMiddle.Value
Records!LastName.Value = Me!txtLastName.Value
Records!Email.Value = Me!txtEmail.Value
Records!Phone.Value = Me!txtPhone.Value
Records!Church.Value = Me!txtChurch.Value
Records!Group.Value = Me!txtGroup.Value
Records!Council.Value = Me!txtCouncil.Value
Records!ParCo.Value = Me!chkParCo.Value
Records!MailAdd.Value = Me!txtMailAdd.Value
Records.Update
Records.Close
Basically you need double quotes qaround the text, so for that you can use CHR(34)
strSQL = "INSERT INTO tblVolunteers " & vbCrLf & _
"VALUES (" & CHR(34) & [txtTitle] & CHR(34) & "," & CHR(34) & [txtFirstName] & CHR(34) & "," & CHR(34) & [txtMiddle] & CHR(34) & "," & CHR(34) & [txtLastName] & CHR(34) & "," & CHR(34) & [txtEmail] & CHR(34) & _
"," & CHR(34) & [txtPhone] & CHR(34) & "," & CHR(34) & [txtChurch] & CHR(34) & "," & CHR(34) & [txtGroup] & CHR(34) & "," & CHR(34) & [txtCouncil] & CHR(34) & "," & CHR(34) & [chkParCo] & CHR(34) & "," & CHR(34) & _
[txtMailAdd] & CHR(34) & ");"
use Access Query Design View..... start with just a single field, and then build field by field...
you can toggle it to SQl View to see the syntax
i had this error when i was trying to INSERT records to a local table with VBA.
I have checked the data type and putting in the quotes for the the short text data type but it doesn't work.
table_newid = "SELECT Cint(t1." & id_name(i) & "_new), " & Replace(select_column_str, local_table_name, "t2") & " FROM " & vbCrLf & _
"(SELECT CInt(DCount(""[" & id_name(i) & "]"", """ & qry_distinct_id_name & """, ""[" & id_name(i) & "]<="" & [" & id_name(i) & "])) as " & id_name(i) & "_new, * FROM " & qry_distinct_id_name & ") AS t1 " & vbCrLf & _
"LEFT JOIN " & local_table_name & "_ALL as t2 " & vbCrLf & _
"ON t1." & id_name(i) & " = t2." & id_name(i) & " " & vbCrLf & _
"WHERE t2.database = '" & database_name & "'"
strQuery = "INSERT INTO " & local_table_name & "_temp (" & temp_field(i) & ", " & Replace(select_column_str, local_table_name & ".", "") & ") " & vbCrLf & table_newid
Debug.Print strQuery
DoCmd.SetWarnings False
db.Execute strQuery
DoCmd.SetWarnings True
From the debug.print, i have got:
INSERT INTO TblLUMachineTypes_temp (MachTypeID_new, MachTypeID, MachTypeCode, MachTypeMod, MachTypeDesc, MachTypeDisc, NewCode, Approved, mttime, CreatedBy, CreatedTS, ModifiedBy, ModifiedTS)
SELECT t1.MachTypeID_new, t2.MachTypeID, t2.MachTypeCode, t2.MachTypeMod, t2.MachTypeDesc, t2.MachTypeDisc, t2.NewCode, t2.Approved, t2.mttime, t2.CreatedBy, t2.CreatedTS, t2.ModifiedBy, t2.ModifiedTS FROM
(SELECT CInt(DCount("[MachTypeID]", "qry_TblLUMachineTypes_id_distinct", "[MachTypeID]<=" & [MachTypeID])) as MachTypeID_new, * FROM qry_TblLUMachineTypes_id_distinct) AS t1
LEFT JOIN TblLUMachineTypes_ALL as t2
ON t1.MachTypeID = t2.MachTypeID
WHERE t2.database = 'CPM-252-2'
When i copied this query and execute it manually, it works fine but not with VBA. Any idea?
Thanks in advance.
Remove all the & vbCrLf from your code, they are not necessary and I assume they corrupt the SQL syntax.
I found the problem. I found that qry_distinct_id_name query table has a Dlookup function in there that returns a string value, which will work when executing the query manual but doesn't work when you run it with VBA. So I have re-written the code to put in the quote before and after dlookup() function.
My code is exiting out of the sub on the line that says "CurrentDb.Execute strSQL_Insert_Data". Do you know why this is happening?
Local_Array = Array("dbo_Tape_Capture_Local_tbl", "dbo_Tape_Local_tbl", "dbo_Tape_Memo_Local_tbl")
Server_Array = Array("dbo_Tape_Capture", "dbo_Tape", "dbo_Tape_Memo")
For i = 0 To UBound(Local_Array)
strSQL_Insert_Data = "INSERT INTO [" & Local_Array(i) & "] " & _
"SELECT [" & Server_Array(i) & "].* " & _
"WHERE (LEFT([" & Server_Array(i) & "].header__situs_loan_id," & _
Len([Forms]![Login Page]![CBO_Job_Select_Login]) & ") = " & _
"[Forms]![Login Page]![CBO_Job_Select_Login]);"
CurrentDb.Execute strSQL_Insert_Data
CurrentDb.Close
Next i
--Added Printed out code--
INSERT INTO [dbo_Tape_Capture_Local_tbl] SELECT [dbo_Tape_Capture].*
WHERE (LEFT([dbo_Tape_Capture].header__situs_loan_id,14) = [Forms]![Login Page]![CBO_Job_Select_Login]);
There is missing FROM TableName in your query. Replace TableName with Actual Table Name
strSQL_Insert_Data = "INSERT INTO [" & Local_Array(i) & "] " & _
"SELECT [" & Server_Array(i) & "].* " & _
"FROM [" & Server_Array(i) & "] " & _
"WHERE (LEFT([" & Server_Array(i) & "].header__situs_loan_id," & _
Len([Forms]![Login Page]![CBO_Job_Select_Login]) & ") = " & _
"[Forms]![Login Page]![CBO_Job_Select_Login]);"
Having the weirdest problem ever. I do have an sql insert statement, that properly works in sql. When i put that sql into vba it works very good from my pc. However, it does not work and shows sql error: missing comma. Where can be the problem??? I use Access 2010 plus, others use same Access version and having same ODB connections (DSN servers) . Some code example:
sql = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST= ODB)(PORT=1520))" & _
"(CONNECT_DATA=(SERVICE_NAME=ABTL))); uid=IN; pwd=XXX;"
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset
Set cmd = New ADODB.Command
con.Open sql
Set db = CurrentDb()
Set rst = db.OpenRecordset(strSQL)
Do While Not rst.EOF
insetSQL = con.Execute(" INSERT INTO STOCK (PNM_AUTO_KEY, PN, DESCRIPTION, HISTORICAL_FLAG, qty_oh, qty_adj, qty_available, CTRL_NUMBER, CTRL_ID, receiver_number, rec_date, serial_number,pcc_auto_key, cnc_auto_key, loc_auto_key, whs_auto_key, unit_cost, adj_cost, stc_auto_key, visible_mkt, remarks, ifc_auto_key, exp_date, unit_price, tagged_by, tag_date, owner, PART_CERT_NUMBER,ORIGINAL_PO_NUMBER, SHELF_LIFE, CTS_AUTO_KEY, MFG_LOT_NUM, AIRWAY_BILL )" & _
" VALUES ( " & rst![minimumas] & ", '" & rst![pn] & "', '" & "FROM_SCRIPT" & "', '" & "F" & "'," & rst![qty_oh] & "," & rst![qty_oh] & "," & rst![qty_oh] & "," & "G_STM_CTRL_NUMBER.nextval" & "," & "1" & ", '" & rst![receiver_number] & "', " & " TO_DATE('" & rst![rec_date] & "','YYYY-MM-DD'), '" & rst![serial_number] & "'," & rst![pcc_auto_key] & "," & rst![cnc_auto_key] & "," & rst![loc_auto_key] & "," & rst![whs_auto_key] & "," & rst![unit_cost] & "," & rst![unit_cost] & "," & "1" & ",'" & "T" & "', '" & rst![remarks] & "'," & _
"1" & ", " & " TO_DATE('" & rst![exp_date] & "','YYYY-MM-DD'), " & "0" & ",'" & rst![TAGGED_BY] & "', " & " TO_DATE('" & rst![tag_date] & "','YYYY-MM-DD'), '" & "" & "', '" & rst![PART_CERT_NUMBER] & "', '" & rst![ORIGINAL_PO_NUMBER] & "', '" & rst![SHELF_LIFE] & "', " & rst![CERT_SOURCE] & ", '" & rst![MFG_LOT_NUM] & "', '" & rst![AIRWAY_BILL] & "'" & " )")
Loop
It might be that one of the rescordset fields that is a string data type, has a value that contains a comma but you have not treated it as string.
eg
VALUES ( " & rst![minimumas] & ",
For the above code to work minimumas CANNOT contain any commas.
Are you certain that all the string fields int he recordset have been appended to the SQL string with a ' around them.
We need to see the sql string is created which then causes the error. Please provide this as requested.
=========================================================
PART 2 Viewing the SQL causing the error
replace
insetSQL = con.Execute(
with
on error resume next
strMySQl = the string currently used in the execute statement
insetSQL = con.Execute(strMySQl)
if err.number <> 0 then
stop
debug.print err.number, err.description
debug.print strMySQl
end if
then post the sql string that is printed in the immediate window to this site.
I would also suggest that you compare the SQL string generated on your machine with the other machines - just in case something weird is happening.
I am new to using Access 2010. I wish to execute the following sql update statement, but I have problems with the syntax. The table is called "Forecasts", and users will edit & update the qty forecasted.
Problem - The table fieldnames are 2014_1, 2014_2, 2014_3 ... to represent the different months, stored in an array. I have done abit of research and I believe the way to dynamically do this is:
Dim sqlString As String
sqlString = "UPDATE Forecasts " & _
" SET Branch_Plant=" & Me.txtBranch_Plant & _
", Item_Number_Short='" & Me.txtItem_Number_Short & "'" & _
", Description='" & Me.txtDescription & "'" & _
", UOM='" & Me.txtUOM & "'" & _
", Estimated_Cost=" & Me.txtEstimated_Cost & _
", Requesting_Business_Unit='" & Me.txtRequesting_Business_Unit & "'" & _
", End_Customer='" & Me.txtEnd_Customer & "'" & _
", Project='" & Me.txtProject & "'" & _
", Forecasts." & "[" & arrMonthToDisplay(0) & "]" = " & Me.txtProjectedJanVolume " & _
" WHERE ID =" & Me.txtID.Tag
MsgBox ("This is the output: " & sqlString)
CurrentDb.Execute sqlString
It was working fine until this line was added
Forecasts." & "[" & arrMonthToDisplay(0) & "]" = " & Me.txtProjectedJanVolume
The msgbx output now shows: "False". Whats wrong with sqlString?
Please help! Thank you very much.
", Forecasts.[" & arrMonthToDisplay(0) & "] = " & Me.txtProjectedJanVolume & _
" WHERE ID =" & Me.txtID.Tag
You compare string to string.
Change
", Forecasts." & "[" & arrMonthToDisplay(0) & "]" = " & Me.txtProjectedJanVolume " &
to
", Forecasts." & "[" & arrMonthToDisplay(0) & "] = " & " Me.txtProjectedJanVolume " &