SQL String syntax error in VBA - sql

I have this SQL string
theSQL = "INSERT INTO tbl_PROJECTS (co_id, contact_id, prop_id, worktype_id, incharge_id, project_name, project_ref," _
& "project_status, project_awardref, project_awarddate, project_startdate, project_targetdate," _
& "project_completedate, project_finalreportdate, project_location, project_notes)"
theSQL = theSQL & " VALUES (" & theCoID & "," & theContactID & "," & thePropID & "," & theWorkTypeID & "," & theInCharge & "," _
& "'" & theProjectName & "'" & "," & theProjectRef & "," & theProjectStatus & "," & theAwardRef _
& theAwardDate & "," & theStartDate & "," & theTargetDate & "," & theCompleteDate & "," & theFinalReportDate & "," _
& theLocation & "," & theNotes & ")"
When I do DoCmd.RunSQL (theSQL) I get syntax error (runtime error 3134).
I sent the output to Debug.Print. Can't find what is wrong with the syntax.
Anyone who can tell what is wrong with this sql command from VBA?
Some variables are null like thetargetdate and thecompletedate and I did not include the projectID in this query because it is autonumber. I want the number generated automatically.
Is it not allowed to pass null value to SQL?
Thanks
DEBUG PRINT RESULT :
INSERT INTO tbl_PROJECTS (co_id, contact_id, prop_id, worktype_id,
incharge_id, project_name, project_ref, project_status,
project_awardref, project_awarddate, project_startdate,
project_targetdate, project_completedate, project_finalreportdate,
project_location, project_notes) VALUES (61,66,134,1,1,'STRUCTURAL
DESIGN',,AWARDED,Test LPO,2/11/2016,,,,,Dnata 4 storey warehouse,)

Is it not allowed to pass null value to SQL?
It is, but it can't be done by stating a space. You must write Null:
VALUES (61,66,134,1,1,'STRUCTURAL DESIGN',Null,'AWARDED','Test LPO',#2/11/2016#,Null,Null,Null,Null,'Dnata 4 storey warehouse Alquoz',Null)
and quotes and date delimiters are missing.

You wrote this:
theSQL = "INSERT INTO tbl_PROJECTS (co_id, contact_id, prop_id, worktype_id, incharge_id, project_name, project_ref," _
& "project_status, project_awardref, project_awarddate, project_startdate, project_targetdate," _
& "project_completedate, project_finalreportdate, project_location, project_notes)"
theSQL = theSQL & " VALUES (" & theCoID & "," & theContactID & "," & thePropID & "," & theWorkTypeID & "," & theInCharge & "," _
& "'" & theProjectName & "'" & "," & theProjectRef & "," & theProjectStatus & "," & theAwardRef _
& theAwardDate & "," & theStartDate & "," & theTargetDate & "," & theCompleteDate & "," & theFinalReportDate & "," _
& theLocation & "," & theNotes & ")"
In the second line in the second block, there's no ending quotes.

Related

Using INSERT INTO with VALUES fails with Run-time error '3078'

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

Missing comma error error inserting sql through access 2010 vba

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.

VBA query Inserting Time instead of Date

I need some help with my query I am trying to insert to a table see above code:
CurrentDb.Execute ("INSERT INTO tblWarehouseItem ( whiwrhID, whiItemName, whivatName," whiVatRate, whiimtID, whiQty, whiPrice, whisupID, whiDateIn, whiExpiryDate,whiwhiID ) " & _
" Values (" & rs!WID & "," & Chr(34) & rs!N & Chr(34) & "," & Chr(34) & rs!VN & Chr(34) & "," & rs!VR & "," & rs!IID & "," & intQtyForm & "," & rs!PR & "," & rs!SID & "," & CDate(rs!DIN) & "," & CDate(rs!EXD) & "," & rs!ID & ")")
In my table the CDate(rs!EXD) and CDate(rs!DIN) are stored as time.
When I compile my query in the immediate window I get Dates.
INSERT INTO tblWarehouseItem ( whiwrhID, whiItemName, whivatName, whiVatRate, whiimtID, whiQty, whiPrice, whisupID, whiDateIn, whiExpiryDate,whiwhiID ) Values (2,"ITEM10","A",19,14,4,20,10,21/07/14,26/05/14,60)
How can I make my query to insert the date in the table?
thanks in advance
If you run that 21/07/14 is passed to Access and interpreted as an integer resulting from 12 divide by 7 divide by 14 which when converted to a date is just a time.
Delimit dates with #:
.. ",#" & CDate(rs!DIN) & "#," ..

Using variables in fieldnames - SQL Update statement

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 " &

Number of query values and destination fields are not the same in vb6 Error

I want to ask something,
I wrote the code like this, but when I execute that, it contain an error like this
"Number of query values and destination fields are not the same"
Before I show my code, I'll show you my structural table :
No : AutoNumber
NoNota : Text
NamaMotor : Text
NamaPeg : Text
Unit : Number
TotalJasa : Number
TotalPart : Number
GrandTotal : Number
Here's my code below :
dung = "INSERT INTO TmpTransaksi VALUES (" & _
"" & TBox(33).Text & "," & _
"'" & TBox(0).Text & "'," & _
"'" & TBox(32).Text & "'," & _
"'" & TBox(30).Text & "'" & _
"" & TBox(25).Text & "," & _
"" & TBox(23).Text & "," & _
"" & TBox(15).Text & "," & _
"" & TBox(16).Text & ")"
MsgBox dung
cn.Execute dung
Can you tell me where's my fault and correct it?
Thanks before..
You missed a comma. Change
"'" & TBox(30).Text & "'" & _
^^^
to
"'" & TBox(30).Text & "'," & _
On a side note: consider to learn and use parameterized queries instead of interpolating query strings.