Getting SQL Syntax Error in INSERT INTO statement in Access 2010 - sql

I have written the following Insert Into statement in Access 2010 VBA:
Private Sub AddBPSSButton_Click()
' CurrentDb.Execute "INSERT INTO TabClearDetail(C_Site) VALUES(" & Me.C_Site & ")"
Dim strSQL As String
'MsgBox Me.[Clearance Applying For]
'MsgBox Me.[Contract Applying for]
'MsgBox Me.[C_Site]
'MsgBox Me.[C_SponsorSurname]
'MsgBox Me.[C_SponsorForename]
'MsgBox Me.[C_SponsorContactDetails]
'MsgBox Me.[C_EmploymentDetail]
'MsgBox Me.[C_SGNumber]
'MsgBox Me.[C_REF1DateRecd]
'MsgBox Me.[C_REF2DateRecd]
'MsgBox Me.[C_IDDateRecd]
'MsgBox Me.[C_IDNum]
'MsgBox Me.[C_CriminalDeclarationDate]
'MsgBox Me.[Credit Check Consent]
'MsgBox Me.[C_CreditCheckDate]
'MsgBox Me.[Referred for Management Decision]
'MsgBox Me.[Management Decision Date]
'MsgBox Me.[C_Comment]
'MsgBox Me.[C_DateCleared]
'MsgBox Me.[C_ClearanceLevel]
'MsgBox Me.[C_ContractAssigned]
'MsgBox Me.[C_ExpiryDate]
'MsgBox Me.[C_LinKRef]
'MsgBox Me.[C_OfficialSecretsDate]
strSQL = "INSERT INTO TabClearDetail(Clearance Applying For, Contract Applying for, " & _
"C_Site, C_SponsorSurname, C_SponsorForename, C_SponsorContactDetails, C_EmploymentDetail, " & _
"C_SGNumber, C_REF1DateRecd, C_RED2DateRecd, C_IDDateRecd, C_IDNum, " & _
"C_CriminalDeclarationDate, Credit Check Consent, C_CreditCheckDate, Referred for Management Decision, " & _
"Management Decision Date, C_Comment, C_DateCleared, C_ClearanceLevel, C_ContractAssigned, " & _
"C_ExpiryDate, C_LinkRef, C_OfficialSecretsDate) VALUES('" & Me.[Clearance Applying For] & "', " & _
"'" & Me.[Contract Applying for] & "', '" & Me.[C_Site] & "', '" & Me.[C_SponsorSurname] & "', " & _
"'" & Me.[C_SponsorForename] & "', '" & Me.[C_SponsorContactDetails] & "', " & _
"'" & Me.[C_EmploymentDetail] & "', '" & Me.[C_SGNumber] & "', '" & Me.[C_REF1DateRecd] & "', " & _
"'" & Me.[C_REF2DateRecd] & "', '" & Me.[C_IDDateRecd] & "', '" & Me.[C_IDNum] & "', " & _
"'" & Me.[C_CriminalDeclarationDate] & "', '" & Me.[Credit Check Consent] & "', '" & Me.[C_CreditCheckDate] & "', " & _
"'" & Me.[Referred for Management Decision] & "', '" & Me.[Management Decision Date] & "', " & _
"'" & Me.[C_Comment] & "', '" & Me.[C_DateCleared] & "', '" & Me.[C_ClearanceLevel] & "', " & _
"'" & Me.[C_ContractAssigned] & "', '" & Me.[C_ExpiryDate] & "', '" & Me.[C_LinKRef] & "', " & _
"'" & Me.[C_OfficialSecretsDate] & "');"
DoCmd.RunSQL (strSQL)
'MsgBox strSQL
End Sub
All The MsgBox calls work, so I believe I have typed all column names and text box names correctly. I am getting a Syntax error when I get to the DoCmd.RunSQL line. Have been staring at this for quite a while trying to see if I have missed a comma or speech mark or something, but am hoping maybe another set of eyes will see my mistake.
Any help will be greatly appreciated.
Thanks!

When you have spaces in your object names you need to enclose the full name in brackets. So where you have:
INSERT INTO TabClearDetail(Clearance Applying For, Contract Applying for,...
It should be
INSERT INTO TabClearDetail([Clearance Applying For], [Contract Applying for],...
For what it's worth I personally can't stand special characters in object names for exactly this reason, if it's not too late you should consider renaming your columns. Pascal Case is usually clear enough for compound names, e.g. ClearanceApplyingFor. Or use under scores - Clearance_Applying_For.
I also think the convention in Access is to qualify dates with # rather than single quotes, i.e. #01/01/2014#, instead of `01/01/2014'

Either you try enclosing the date fields with "#" instead of "'" or change your database's "SQL Server Compatible Syntax" property.

Related

When I write code inside textbox doesn't accept it

I have a textbox in a form. I use this textbox to write "Codes" and then I save it in the table in the database through the SQL insert statement, but the code doesn't accept to run and gives me an error message:
Run-Time error '3075'.
type of database: Access database
type of field data: LongText
What the problem and how to pass all same problems when I need to save codes inside the database field.
When I try to save the code without (') it's working!
I use this SQL Statement:
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Me.txtID & ",
[Code_Title]='" & Me.txtTitle & "'" _
& " ,[Code_Des]= '" & Me.txtDes & "',[Code_Key]= '" & Me.txtKey & "',
[Notes]= '" & Me.txtNotes & "'" _
& " Where [ID]= " & Me.txtID1 & ""
And I want to save this Code:
DSum("Field1";"Table";"Field2= '" & Value & "'")
Please change your code as follows. You need to escape single quotes by doubling them up. A simple replace will work for your.
CurrentDb.Execute "Update Tbl_Codes Set [LP_ID]= " & Replace(Me.txtID,"'","''") & ",
[Code_Title]='" & Replace(Me.txtTitle,"'","''") & "'" _
& " ,[Code_Des]= '" & Replace(Me.txtDes,"'","''") & "',[Code_Key]= '" & Replace(Me.txtKey,"'","''") & "',
[Notes]= '" & Replace(Me.txtNotes,"'","''") & "'" _
& " Where [ID]= " & Me.txtID1 & ""
DSum("Field1";"Table";"Field2= '" & Replace(Value,"'","''") & "'")

VBA Insert static value into SQL table

I've used VBA to insert into an SQL table before but its always been using values in cells. I have three columns in my table where I need to add just a static value (so no cell reference).
The code I have so far is:
stSQL = "INSERT INTO Client_Notes " & _
"(ID, Category, RefID, Name, Notes, Date_Loaded, Latest) " & _
" VALUES (" & _
"'" & 1 & "', " & _
"'" & 1 & "', " & _
"'" & Sheets("Missing").ActiveCell.Offset(0, -10).Value & "', " & _
"'" & Sheets("Missing").ActiveCell.Offset(0, -9).Value & "', " & _
"'" & Sheets("Details").ActiveCell.Value & "', " & _
"'" & Date & "', " & "'" & _
"'" & 1 & "'" & _
")"
The error I keep getting is when trying to insert 1 as a value. I'm sure its straight forward but feel like I had tried every quote and comma combination going.
Thanks in advance
So the new code now looks like so, where I am getting Subscript Out Of Range:
stSQL = "INSERT INTO Client_Notes " & _
"(ID, Category, RefID, Name, Notes, Date_Loaded, Latest) " & _
" VALUES (" & _
"1, " & _
"1, " & _
"'" & Sheets("Missing").Range("L" & i).Offset(0, -10).Value & "', " & _
"'" & Sheets("Missing").Range("L" & i).Offset(0, -9).Value & "', " & _
"'" & Sheets("Details").Range("L" & i).Value & "', " & _
"'" & Date & "', " & _
"1)"

MA run-time error '3075' Syntax Error

i have this code and it shows me run-time error '3075' Syntax Error and i dont know how to fix it . help me please
CurrentDb.Execute "UPDATE PUNONJESIT set Id_punonjesit= '" & Me.id & "', Emer_punonjesi ='" & Me.emri & "', Mbiemer_punonjesi='" & Me.mbiemri & ", Mosha='" & Me.mosha & "', Profesioni='" & Me.profesioni & "', Rroga='" & Me.rroga & "', WHERE Id_punonjesit ='" & Me.id & "'"
I'm not sure the manual data (e.g. Me.id) is retrieve from text box properties or otherwise? If they are text boxes, then you should change them to this (e.g. Me.id.value) so the access can retrieve the value.
Here is my suggestion below:
(You)
CurrentDb.Execute "UPDATE PUNONJESIT set Id_punonjesit= '" & Me.id & "', Emer_punonjesi ='" & Me.emri & "', Mbiemer_punonjesi='" & Me.mbiemri & ", Mosha='" & Me.mosha & "', Profesioni='" & Me.profesioni & "', Rroga='" & Me.rroga & "', WHERE Id_punonjesit ='" & Me.id & "'"
(Me)
CurrentDb.Execute "UPDATE PUNONJESIT set Id_punonjesit=" & Me.id.value & ", Emer_punonjesi =" & Me.emri.value & ", Mbiemer_punonjesi=" & Me.mbiemri.value & ", Mosha=" & Me.mosha.value & ", Profesioni=" & Me.profesioni.value & ", Rroga=" & Me.rroga.value & ", WHERE Id_punonjesit =" & Me.id.value & ";"
You can try it and see what error does it generate. Do let me know if it helps? (:

Date exception in German windows during insert MS access vb.net

I have written an insert query which inserts datetime along with other columns. It works fine for all locations except when
my German client logs in and runs the application it gives him below error. I have formatted the datevalue to yyyy-mm-dd to make
culture independent.
MS access database is stored in a server in US.
German client is running application from Germany.
strDateSubmit = dtpDateSub.Value.ToString("yyyy-MM-dd")
strSaveOSTR = "INSERT INTO " & strOSTR & " ([OSTR #],[OSTR Type],[# of Samples],[RA#],[Customer],[SKF #],[Test Description]," & _
"[TestLength],[TestUnit],[TestLengthDays],[Requestor],[Date Submitted],[Seals Avail],[Fixtures Available],[Peripherals Avail],[PO Avail]," & _
"[Machine Type],[Hours to Process],[Location],[Current Status],[ErrorsPresent],[ContaminType]" & SampleREcvd1 & ", [Emp_ID],[Industry])" & _
" Values ( '" & strOSTRNum & "', '" & cmbOSTRTypes.Text & "', " & intSamples & ", '" & strRA & "', '" & strCustomer & "', '" & strSKFNum & _
"', '" & strTestDescr & "', " & intTestLength & ", '" & strTestUnits & "', '" & txtTestLDays.Text & "', '" & strRequestor & "', #" & strDateSubmit & "#, '" & strSealAvail & _
"', '" & strFixtAvail & "', '" & strPheriAvail & "', '" & strPOAvail & "', '" & strMachineClass & "', " & intHrstoProc & ",'" & g_objProp.Location & _
"', '" & strStatus & "', '" & ErrorsPresent & "', '" & ContaminationType & "'" & SampleREcvd2 & ", '" & emp_id & "', '" & Industry & "')"
Error: Syntaxfehler in Datum in Abfrageausdruck '#01.02.2016'
Do yourself a favor: Scrap the dynamic SQL and use a parameterized query, e.g.,
sampleSQL = "INSERT INTO TableName ([Date Submitted]) VALUES (?)"
Dim cmd = New OleDbCommand(sampleSQL, conn)
cmd.Parameters.AddWithValue("?", dtpDateSub.Value)
cmd.ExecuteNonQuery()
That way you can use the actual DateTime value returned by the DateTimePicker. You don't have to be concerned with locale settings or string formats or any of those aggravations.
You may need a more strict format of the date expression string:
strDateSubmit = dtpDateSub.Value.ToString("yyyy'/'MM'/'dd")
This will always return a date like "2016/02/01" (no dots or dashes), and it will concatenate correctly here:
"', #" & strDateSubmit & "#, '"
as you intend.

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.