Runtime Error 3134 - Syntax Error in INSERT INTO Statement - ms-access

I'm trying to fix it about hour but it's not work Please help me :(
CurrentDb.Execute "INSERT INTO match_day( home_team, away_team, date, time, home_score, away_score, stadium) " & _
" VALUES('" & Me.textHT & "','" & Me.textAT & "',#" & Me.textDATE & "#,#" & Me.textTime & "#," & Me.textHS & "," & Me.textAS & ",'" & Me.textSTD & ",')"

Are the fields for date and time considered reserved words and should be wrapped in brackets or ticks to qualify it as the column name...
..., [date], [time], ...
But I think it is most likely the trailing final comma before your final closing ) of the inserted values making it look like it wants another field to be inserted.
Me.textSTD & ",')"
change to
Me.textSTD & "')"

I ran into a similar error - thanks to this post I realised that I had used a reserved name "note" in a table ( instead of "notes").
StrSQL = "INSERT INTO option_notes ( OPTION_ID , USER_ID , [NOTE] ) VALUES ( " & currID & " , " & currUserID & " , '" & currNote & "' ) ; "
CurrentDb.Execute StrSQL
I ended up changing the field name - however, wrapping the field name with [ ] allowed the code to execute correctly.

Related

Insert a value into a table while creating a record in another table

I'm out of my league on this... Another developer before me did something similar to what I want to do by adding a value in a table while updating another table. However, he was running updates as well as inserting, and his primary key was text. Mine PK is integer. Here's his code (works great) that I am trying to reverse engineer and apply to my situation:
Dim sqlQuery As String
sqlQuery = "IF EXISTS (SELECT ReportPK FROM
ACIST_MobilePipelineReportReviewed WHERE ReportPK = '" & ReportPk & "') " &
_
" UPDATE ACIST_MobilePipelineReportReviewed set Status = 'Approved'
WHERE ReportPK = '" & ReportPk & "'" & _
" ELSE " & _
" INSERT INTO ACIST_MobilePipelineReportReviewed ([ReportPK],
[PipelineUID],[ReportDate],[ReportInspector],[Status]) VALUES (" & _
"'" & ReportPk & "','" & Me!PipelineUID & "','" & Me!ReportDate & "','"
& Me!ReportInspector & "','Approved')"
End Sub
Here's what I'm doing: I have a combo box on a form called FacilityEntryF. That form is tied to my FacilityT table. I am selecting "CampaignID" from the CampaignT table and adding it to the FacilityT using that combo box in the aforementioned form. No biggie there... Works great.
The FacilityT has many columns of which I have [FacilityID] which is the primary key and is an autogenerated integer. It also has a column for [CampaignID] which is a foreign key from the CampaignT table.
After adding the CampaignID and starting a new FacilityID in FacilityT, I also want to create a new record in my CampaignFacilityParticipationT table. That table consists of only three columns: CampaignFacilityParticipationID, CampaignID, ParticipantFacilityID. I want to take the new [FacilityID] and the [CampaignID] I added to that table and insert them into the CampaignFacilityParticipationT table (FacilityID goes into the ParticipantFacilityID column). Here's the code below that didn't work (which I'm not surprised because I don't know what I'm doing):
Dim sqlQuery As String
sqlQuery = "IF EXISTS (SELECT FacilityID FROM FacilityT WHERE FacilityID =
" & FacilityID) " & _
" INSERT INTO CampaignFacilityParticipationT ([CampaignFacilityParticipationID],[CampaignID],[ParticipantFacilityID]) VALUES (" & _
"" & CampaignFacilityParticipationID,'" & Me!CampaignID," & Me!ParticipantFacilityID, CampaignID)"
End Sub
Using MS Access 2013 with Microsoft SQL backend.
Thanks!!!
Concatenation is not correct. If apostrophes are needed to delimit parameters then make sure they are used consistently. Normally in Access, apostrophes would only be used for text fields, # for date/time and nothing for number. Maybe because backend is MS SQL apostrophes are needed for all field types? Why do you repeat CampaignID in VALUES clause?
sqlQuery = "IF EXISTS (SELECT FacilityID FROM FacilityT WHERE FacilityID = '" & Me!FacilityID & "')" & _
" INSERT INTO CampaignFacilityParticipationT ([CampaignFacilityParticipationID],[CampaignID],[ParticipantFacilityID])" & _
" VALUES ('" & Me!CampaignFacilityParticipationID & "','" & Me!CampaignID & "','" & Me!ParticipantFacilityID & "')"
Is it possible for you to use a subform on FacilityEntryF on which you select the CampaignID? That will eliminate the need for this code.

ms-Access is removing leading zeros from a string

In the below code, the value of skuSet.Fields(0), which is a text field in the database, is "000000002".
If skuSet.RecordCount = 0 Then
sql = "SELECT Stock_Code FROM Stock WHERE Stock_Code = '" & stkLine.StockCode & "'"
Set skuSet = dbStock.OpenRecordset(sql, dbOpenDynaset)
End If
sql = "SELECT * FROM PickedByPicco WHERE OrderID = " & stkLine.OrderId & " AND StockCode = '" & skuSet.Fields(0) & "'"
Set SOPSLineSet = dbSOPS.OpenRecordset(sql, dbOpenDynaset)
If SOPSLineSet.RecordCount = 0 Then
sql = "INSERT INTO PickedByPicco(OrderID, StockCode, Qty, ScannedBy, ProcessedBy, processed) VALUES(" & stkLine.OrderId & _
", " & skuSet.Fields(0) & ", " & stkLine.Quantity & ", '" & stkLine.UserId & "', '', False)"
dbSOPS.Execute (sql)
When I step through the code, the value in skuSet.Fields(0) is still the same, as expected.
When the query has been executed, I check the PickedByPicco table, and the StockCode field shows just a value of 2 instead, and it's removed all of the leading 0's.
Why would it be doing this and how can I stop it?
That's because your INSERT statement looks like this:
INSERT INTO PickedByPicco (...) VALUES (..., 000000002, ...)
when it should look like this:
INSERT INTO PickedByPicco (...) VALUES (..., '000000002', ...)
(Note the quotes around your value.)
Normally, I'd tell you to use parameterized SQL, because SQL creation by string concatenation is evil, but, unfortunately, DAO's Database.Execute does not support that. So, the next best thing is to properly escape strings. To do that:
put single quotes around your value and
escape any single quotes occurring in your value:
I.e. this line
", " & skuSet.Fields(0) & ", " & ...
becomes
", '" & Replace(skuSet.Fields(0), "'", "''") & "', " & ...
While you are at it, be sure to replace single quotes in your other strings as well! Currently, a UserId of O'Brien would break your SQL, and other values might do worse.

Check if Exist or Not then Insert Update

I need to check if the data exist if the data didn't exist then I'll be able to insert and update but if the data exist the messagebox will show that the data already exist but when I tried to add same data that already exist it still add and no messagebox shown that it already exist.
here's my code
If jobtitle <> "" And businessunit <> "Please Select" And division <> "Please Select" And subdivision <> "Please Select" And classification <> "Please Select" And subclassification <> "Please Select" Then
insrtResult = UpdateInsDelRecord("UPDATE EMP_MASTERTBL SET JOBTITLE = '" & jobtitle & "' " & _
"WHERE MASTERID = '" & empID & "'" & _
";" & _
"INSERT INTO EMPGROUP_TBL(MASTERID, BUSINESS_UNIT, " & _
"DIVISION, SUB_DIVISION, CLASSIFICATION, SUB_CLASSIFICATION) VALUES " & _
"('" & HandleQuote(empID) & "', " & _
"'" & businessunit & "' ," & _
"'" & division & "' ," & _
"'" & subdivision & "' ," & _
"'" & classification & "' ," & _
"'" & subclassification & "')")
If Not insrtResult Then
MessageBox("alert('Error Ocurred While Inserting a Data.')")
Else
MessageBox("alert('Successfully Added.')")
End If
Else
MessageBox("alert('Data Already Exist.')")
End If
what could be the problem to my code? Thanks in advance.
For SQL Server check the MERGE query, i used this to perform an "upsert" on my own db, it also seems to be performing fast enough.
You can chose a condition and perform different operations whether it returns true or false (e.g. if ID already exists then update, else insert)
For MySql i think there are solutions much more easier to write, wich unfortunatly i can't remember at the moment
https://msdn.microsoft.com/en-us/library/bb510625.aspx

Adding values into a table with a query

So all I'd like to do is add two queries into a table called tmpGroupSearch. I'm not sure how to do it wit out creating a record set and looping through every record and individually adding them in. I'm thinking there is a much easier way to do this I just can't find the proper structure.
Here are my queries:
"SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
"Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
You can follow an INSERT INTO clause with a list of values, like #Asad shows, or also a SELECT query. Do yourself a favor and always list the field names in your SQL or you are just creating time bombs for the future.
Dim strSelect1 As String
Dim strSelect2 As String
strSelect1 = "SELECT tblGroupHeader.GroupName" _
& ", tblGroupHeader.GroupNum" _
& ", tblAlsoKnown.AlsoKnown" _
& " FROM tblGroupHeader" _
& " LEFT JOIN tblAlsoKnown ON tblGroupHeader.GroupNum = tblAlsoKnown.GroupNum" _
& " WHERE tblGroupHeader.GroupName like '" & txtgroupSearch.Value & "*'" _
& " OR tblGroupHeader.GroupNum like '" & txtgroupSearch.Value & "*';"
strSelect2 = "Select * FROM tblActionLog WHERE AlsoKnown LIKE '" & txtgroupSearch.Value & "*';"
Dim strInsert1 As String
Dim strInsert2 As String
strInsert1 = "INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown) " & strSelect1
'the next version is valid SQL, but *dangerous* because field names are not enumerated
strInsert2 = "INSERT INTO tmpGroupSearch " & strSelect2
It is possible to write the INSERT INTO statement in two forms.
The first form does not specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
Test this parameter query in the Access query designer and adjust as needed so that it returns the row set you expect for the pSearchText parameter value you supply.
PARAMETERS pSearchText Text ( 255 );
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
FROM
tblGroupHeader AS gh
LEFT JOIN tblAlsoKnown AS ak
ON gh.GroupNum = ak.GroupNum
WHERE
gh.GroupName Like "'" & pSearchText & "*'"
OR gh.GroupNum Like "'" & pSearchText & "*'"
UNION ALL
SELECT al.GroupName, al.GroupNum, al.AlsoKnown
FROM tblActionLog AS al
WHERE al.AlsoKnown Like "'" & pSearchText & "*'"
Once you have it returning the correct data, convert it to an INSERT query by changing the beginning of the statement to this ...
PARAMETERS pSearchText Text ( 255 );
INSERT INTO tmpGroupSearch (GroupName, GroupNum, AlsoKnown)
SELECT gh.GroupName, gh.GroupNum, ak.AlsoKnown
... and the rest
Save that query as qryGroupSearchAppend. Then you can execute that query from your VBA code:
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("qryGroupSearchAppend")
qdf.Parameters("pSearchText").Value = Me.txtgroupSearch.Value
qdf.Execute dbFailOnError

vb.net INSERT CURDATE() to MySQL issue

In a windows application I have a query that im trying to insert the current date on my mysql database
query below:
SqlVentaCasas1 = "INSERT INTO VentaCasasHistory (ID, Direccion, Estatus, Precio, " & _
"NumeroDias, FechaHoy, Agente, Compania, Unidad, Ciudad ) VALUES ('" & _
AddIDCasas2 & "','" & AddDireccionCasas2 & "','" & AddEstatusCasas2 & "'," & AddPrecioCasas2 & ", 0, CURDATE(), '" & AgenteNameCasas2 & "','" & AgenteCompaniaCasas2 & "', '" & AddUnidadCasas2 & "', '" & AddCiudadCasas2 & "' );"
CommandVentaCasas1 = New MySqlCommand(SqlVentaCasas1, con)
CommandVentaCasas1.CommandType = CommandType.Text
CommandVentaCasas1.ExecuteNonQuery()
when i input the values that i want to insert into mysql everything runs smoothly except that when i check the database for the date entered i find myself with the 0000-00-00
on the other hand, when i run the same query from PHPmyAdmin
INSERT INTO `VentaCasasHistory`(`ID`, `Direccion`, `Estatus`, `Precio`, `NumeroDias`, `FechaHoy`, `Agente`, `Compania`, `Unidad`, `Ciudad`) VALUES ([String1],[String2],[String3],[Integer1],[Integer2],CURDATE(),[String4],[String5],[String6],[String7])
where FechaHoy is CURDATE() is does insert correctly the date that should be.
I cant seem to find what is the problem, As i understand it will only insert 0000-00-00 if there is something wrong with the date when been entered.
the reason i kept both queries "identical" was to understand what im doing wrong and I know that they can be subject to SQL injection.
your help would be very appreciated.
Leo P.
this is the code i have for the last piece that you told me.
Dim StringDate As String
StringDate = Date.Today.ToString("yyyy-MM-dd")
SqlVentaCasas1 = "INSERT INTO VentaCasasHistory (ID, Direccion, Estatus, Precio, " & _
"NumeroDias, FechaHoy, Agente, Compania, Unidad, Ciudad ) VALUES ('" & _
AddIDCasas2 & "','" & AddDireccionCasas2 & "','" & AddEstatusCasas2 & "'," & AddPrecioCasas2 & ", 0, STR_TO_DATE('" & StringDate & "', GET_FORMAT(DATE,'ISO')), '" & AgenteNameCasas2 & "','" & AgenteCompaniaCasas2 & "', '" & AddUnidadCasas2 & "', '" & AddCiudadCasas2 & "' );"
unfortunately it does not work and i still get the 0000-00-00.
CURDATE() should really be specified as default value used in CREATE TABLE. In other words, you don't need to put it in as part of a query as when you insert a new record the field with default value set to CURDATE() will have the date automatically inserted.
F.ex:
CREATE TABLE MyTable
(
ID int NOT NULL,
MyName varchar(30) NOT NULL,
MyDate datetime NOT NULL DEFAULT CURDATE(),
PRIMARY KEY (ID)
)
INSERT INTO MyTable (MyName) VALUES ('Epistemex')
Will set the MyDate field to CURDATE().
Hope this helps.