MS Access runtime error 3464 - sql

I am working on a database for my work and i'm trying to insert and update values from tables with sql inside the vb editor
This is my code:
Option Compare Database
Private Sub Übernehmen_Click()
Dim strSQL1 As String
Dim strSQL2 As String
Dim strSQL3 As String
Dim ArtikelNr As Integer
Dim Stück As Integer
Dim Lieferant As String
Dim Bestellnr As Integer
Dim EkPreis As String
Dim Mwst As String
Dim Einkaufsort As String
Dim GhIndex As String
Dim Datum As String
Dim Uhrzeit As String
Dim Lager As String
Dim Beschreibung As String
ArtikelNr = [Forms]![Einkauf]![ArtikelNr].Value
Stück = [Forms]![Einkauf]![Stück].Value
Lieferant = [Forms]![Einkauf]![Lieferant].Value
Bestellnr = [Forms]![Einkauf]![Bestellnr].Value
EkPreis = [Forms]![Einkauf]![EK-Preis].Value
Mwst = [Forms]![Einkauf]![Mwst-Satz].Value
Einkaufsort = [Forms]![Einkauf]![Einkaufsort].Value
GhIndex = [Forms]![Einkauf]![GH-Index].Value
Datum = [Forms]![Einkauf]![Datum].Value
Uhrzeit = [Forms]![Einkauf]![Uhrzeit].Value
Lager = [Forms]![Einkauf]![Lager].Value
strSQL1 = "INSERT INTO Einkäufe (ArtikelNr, Stück, Lieferant, Bestellnr, EKPreis, MwstSatz, Einkaufsort, GHIndex) VALUES (" & ArtikelNr & "," & Stück & ",'" & Lieferant & "','" & Bestellnr & "','" & EkPreis & "','" & Mwst & "','" & Einkaufsort & "','" & GhIndex & "');"
Beschreibung = DLast("EinkaufID", "Einkäufe")
strSQL2 = "INSERT INTO Transaktionen VALUES ('" & ArtikelNr & "','" & Datum & "','" & Lager & "','" & Stück & "','EinkaufID ' + '" & Beschreibung & "' ,'Einkauf',NULL,NULL,'" & Uhrzeit & "');"
strSQL3 = "UPDATE Lagerbestand SET Stück = Stück+" & Stück & " WHERE ArtikelNr = '" & ArtikelNr & "' AND Lager = '" & Lager & "';"
DoCmd.RunSQL strSQL1
DoCmd.RunSQL strSQL2
DoCmd.RunSQL strSQL3
End Sub
After trying to press the button it first adds the two entries and stops at the third one just to throw an error saying "Runtime Error: 3464".
After I press debug it marks the line DoCmd.RunSQL strSQL3.
I would appreciate any answer I get.
Many thanks in advance.

A quick google of "Runtime Error 3464" suggests this is a data type mismatch. You'll typically see this when you try to save a date value in a string field or something like that.
Double check the types passed to your SQL statements match the columns they should be saved to - and apply any necessary conversions if you spot differences.
Also one final heads up...by building your SQL string dynamically you are leaving yourself vulnerable to SQL Injection attacks - you should consider using ADOCommands with parameters.

My error was trying to compare an integer with a string. Even though sql does cast it from an integer to a string if you make a new entry, it does not cast it if you want to compare in a where.

Related

Why does "Enter parameter value" appears using INSERT INTO VALUES?

I'm always getting the "enter parameter value error" when I try to run this code. The error refers to idPat, idSP, idPar and measure_value.
I have checked with the debug idPar, idPat, idSP and measure_value and they assume the correct value; the errors comes out when I run sql.
Dim idPar As Integer
Dim idPat As Integer
Dim idSP As Integer
Dim current_fc As String
Dim namePar As String
Dim sql As String
Dim measureValue As Integer
current_fc = TempVars!CurrentUsername
namePar = Me.cmbManualDailyPar.Value
measureValue = Me.txtMeasureValue
idPar = Nz(DLookup("ID_par", "Parameter", "name_par = '" & namePar & "'"), 0)
idPat = Nz(DLookup("ID_patient", "Patient", "fiscal_code = '" & current_fc & "'"), 0)
idSP = Nz(DLookup("ID_SP", "Diagnosis", "ID_patient = " & idPat & ""), 0)
sql = "INSERT INTO Measure(ID_par, measure_value,ID_SP,ID_patient)" & _
" VALUES(idPar,measureValue,idSP,idPat);"
DoCmd.RunSQL sql
Your VALUES part is just text. What you need is:
" VALUES(" & idPar & "," & measureValue & "," & idSP & "," & idPat & ")"
You may also need to enclose text values in database quotes, for example:
" VALUES(" & idPar & ", '" & measureValue & "'," & idSP & "," & idPat & ")"
to enclose measureValue if it is text.

Is it the same to insert into tables from query as from table using VBA?

so this is my code below it works just fine when selecting from a table :
Private Sub cmdStart_Click()
Dim strSql1 As String
Dim strSql2 As String
Dim strSql3 As String
Dim strSql4 As String
Dim qdef As DAO.QueryDef
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Set dbs = CurrentDb
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , format('" & Forms("qoyod").qaed_date & "' , 'dd/mm/yyyy') , sum(sale_bill_total), 167 " & _
"from sale_bill where sale_bill_date between format( '" & Me.cmbQFrom & "' ,'mm/dd/yyyy') and format( '" & Me.cmbQTo & "' ,'mm/dd/yyyy') and sale_bill_type = 1 "
dbs.Execute strSql1
but when I try to select from a query it just wont work
is there something am doing wrong ?
Thanks in advance.
First you'll need to enclose your data correctly:
numbers need no enclosure: 200
string need to be enclosed with ' or ": 'String' or "String"
Dates need to be enclosed with #: #2020-11-22#
When concatenating strings to an SQL string I usually use the single quotes '
So just guessing on what the field data types are, here is what you SQL string should look like:
strSql1 = "insert into qoyod_details (qaed_num,f_year,qaed_date,l_value,Hesab_code) " & _
"select " & Forms("qoyod").qaed_num & " , " & Forms("qoyod").f_year & " , #" & format(Forms("qoyod").qaed_date, "yyyy-mm-dd") & "#, sum(sale_bill_total) , 167 " & _
"from sale_bill where sale_bill_date between #" & format( Me.cmbQFrom, "yyyy-mm-dd") & "# and #" & format(Me.cmbQTo, "yyyy-mm-dd") & "# and sale_bill_type = 1"
dbs.Execute strSql1
To simplify date conversion use the ISO format yyyy-mm-dd, this will prevent any accidental switching between the day and month in certain configurations.
If you're still getting an error, then try printing the result to the Immediate Window like this for troubleshooting:
Debug.Print strSql1
dbs.Execute strSql1
before trying to execute the string.

VBA + SQL Server - Get Last ID Inserted

Hope you can help - I'm having issues getting the last ID after INSERT.
So the environment - Access 2016, SQL Server and VBA
Dim db As DAO.Database
Dim RS As New ADODB.Recordset
Dim sql As String
I have theses declared and then private sub.
Private Sub CreateOrderHeader()
Dim CustomerID As Integer
Dim OrderDate As String
Dim OrderStatus As String
Dim OrderValue As Double
Dim OrderNotes As String
Dim OrderPostageID As String
Dim OrderAddressID As String
Dim OrderBatchID As Integer
Dim OrderPayment As String
Dim OrderCourierID As String
Dim OrderAgentID As Integer
Dim OrderOutstanding As Double
CustomerID = tbxCusID
OrderDate = Format(Now)
OrderStatus = "InProcess"
OrderValue = txtTotal.value
OrderNotes = tbxNotes.value
OrderPostageID = txtPostage.Column(0)
If tbxCustomerAddress = tbxDeliveryAddress Then
OrderAddressID = 3 'default customers address
Else
'NEED TO GET CUSTOMER ADDRESS TO DO
End If
OrderBatchID = cmbBatch.Column(0)
OrderPayment = sPayMethod
OrderCourierID = cbxShipping.Column(0)
OrderAgentID = 0
OrderOutstanding = txtTotal.value
Dim testvar As String
sql = "INSERT INTO dbo_OrderHeader " _
& "(OrdCusID, OrdDate, OrdStatus, OrdValue, OrdNotes, OrdPostageID, OrdDelAddID,OrdBatchID,OrdPaymentMethod, OrdCourierID,ordAgentID, OrdOutstanding,OrdSource) " _
& " VALUES ('" & CustomerID & "' ,'" & OrderDate & "', '" & OrderStatus & "', '" & OrderValue & "', '" & OrderNotes & "', '" & OrderPostageID & "','" & OrderAddressID & "','" & OrderBatchID & "','" & OrderPayment & "','" & OrderCourierID & "','" & OrderAgentID & "','" & OrderOutstanding & "', 1)"
DoCmd.RunSQL (sql)
sql = "SELECT ##IDENTITY As IDT"
RS.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
IDT = RS!IDT
MsgBox ("Succes - OrderHeader" & " '" & IDT & "' ")
End Sub
I was expecting a result from this code:
sql = "SELECT ##IDENTITY As IDT"
RS.Open sql, CurrentProject.Connection, adOpenStatic, adLockReadOnly
IDT = RS!IDT
But that gives me "0" as result.
Can you help please.
Thanks
You can try this :
Set db = CurrentDB
db.Execute(sql)
IDT = db.OpenRecordset("SELECT ##IDENTITY")(0)
Set db = Nothing
NOTE
Don't execute your insert query like DoCmd.RunSQL (sql) Instead follow the above approach.

How to ignore the Null values in Insert query in access

I have the Database table where the Table needs to be updated using a form.
However all the fields in the Form need not be mandatory to be filled.
I am Writing the Below VB code for inserting However I get an error stating that there is a syntax error in the statement.As i understand it is because of the Null Values in the Variable. I understand that I need to use DBNull.Value for all the null Values.
Here the Thing is there are too many fields to check if the value is null or not.
any body suggest if there is a way to do a mass check on the values entered to be null?
VBCode:
Dim StrSQL As String
Dim StrSQL1 As String
Dim tktID As Variant
Dim Assi As Variant
Dim reopened As Variant
Dim valid As Variant
Dim Reopenreason As Variant
Dim ReassignmentAG As Variant
Dim RBSCollab As Variant
Dim SMEconf As Variant
Dim Cloabag As Variant
Dim smeName As Variant
Dim Updat As Variant
Dim Closed As Variant
Dim iss As Variant
Dim ana As Variant
Dim res As Variant
Dim rVariant As Variant
' Assigining values
tktID = Ticket_number.Value
reopened = Ticket_Reopened.Value
valid = Valid_Reopen.Value
Assi = Assiginee.Value
Reopenreason = Reopen_reason.Value
ReassignmentAG = Reassignment_AG.Value
RBSCollab = RBS_Collab.Value
SMEconf = CkBxSMEConfirmation.Value
Cloabag = Collabarated_AG.Value
smeName = SME_Name.Value
Updat = Update.Value
Closed = Issue_Closed.Value
iss = Issue.Value
ana = Analysis.Value
res = Resolution.Value
rdate = Resolve_date.Value
'Insert values into the tables
StrSQL = "INSERT INTO Updates (TicketID,Assiginee,ReassignmentAG,RBSCollab,CollabAG,SMEconfirmation,SMEName,Update,IssueClosed,Issue,Analysis,Resolution,ResolveDate,TicketReopened,ValidReopen,ReopenReason) VALUES ('" & tktID & "','" & Assi & "','" & ReassignmentAG & "','" & RBSCollab & "','" & Cloabag & "','" & SMEconf & "','" & smeName & "','" & Updat & "','" & Closed & "','" & iss & "','" & ana & "','" & res & "','" & rdate & "','" & reopened & "','" & valid & "','" & Reopenreason & "' ) "
DoCmd.RunSQL StrSQL
thanks in advance for your help
I, too, setup my first Access database using lots of unbound controls and SQL statements for moving data around. But this is not the way to use Access. You should be using bound forms where the controls automatically know what the constraints are based on the table/columns they are bound to.
This means much less code for you to write (and maintain), future developers can look at your Access app and know what's going on because it will be done in the Access paradigm, and if you place as much logic into your tables/relationships as possible then if someone comes along and links to your ACCDB or opens the backend they could enter data without entering bad data.
So ultimately this is an XY problem. Get rid of all this code (especially DoCmd.RunSQL) and create a bound form. Put your validation logic in foreign keys, validation rules, and/or data macros in the table.
A simple solution to this problem could be just check for element's value before using in the inset query and if element's value is undefined than set with null.
Pass this value to database in the query.
Do this for each field:
tktID = IIF(ISNULL(Ticket_number.Value),"Null","'" & Ticket_number.Value & "'")
Then instead of this:
VALUES ('" & tktID & "',...
Do this
VALUES (" & tktID & ",...
Or if you don't mind replacing nulls with empty strings:
tktID = Nz(Ticket_number.Value)
will do it.
Of course you should at least make sure no single quotes are in the stings, so even better:
tktID = IIF(ISNULL(Ticket_number.Value),"Null","'" & Replace(Ticket_number.Value,"'","''") & "'")
After building the string for INSERT statment
strSql = "INSERT INTO tblmovimentiServizi ( msid, " _
& " msData, msIdDestinazione, msOraInizioServizio, msOraFineServizio, msAndataRitorno, " _
& " msOraVincoloEntrata, msOraVincoloUscita, msidAnagraficaAutomezzi, msServizioEseguito, msNoteCommenti) " _
& " VALUES ('" & rst!newid & "', #" & rst!msData + Me.g1 & "#, '" _
& rst!msIdDestinazione & "', #" _
& rst!msOraInizioServizio & "#, #" _
& rst!msOraFineServizio & "#, '" _
& rst!msAndataRitorno & "', #" _
& rst!msOraVincoloEntrata & "#, #" _
& rst!msOraVincoloUscita & "#, '" _
& rst!msidAnagraficaAutomezzi & "', " _
& eseguito & ", '" _
& rst!msNoteCommenti & "'" _
& ");"
I added
strSql = Replace(strSql, "''", "null")
strSql = Replace(strSql, "##", "null")
and it works.

How to insert customer details into Orders table

I have an assignment to build a basic database driven e-commerce site. I have a home page, a products page, an orders page, an order confirm page, a shopping cart page and a view current orders page. The site uses an Access database with three tables.
A Customer table, with all of the customer details, (FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode)
A Products table, with all the product information, (ProductID, ProductName, Price, ProductType, Images, ProductDescription).
And an Orders table which contains CustomerID and ProductID.
I'm trying to create an INSERT statement on the orders page so that when the customer inserts their details and presses the submit button the customers table will have a new record inserted. I also want this to create an entry in the orders table and redirect the client to the order confirm page which will display the details of the order.
Here is my code which runs when the submit button is clicked on the order form.
EDIT I've fixed the error with the missing apostrophe. Attempting to insert using two sql commands as I've been told that access databases can't handle two at once. Still getting an error though.
Protected Sub btnAddRecord_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim strFirstName As String
Dim strLastName As String
Dim strEmailAdd As String
Dim intCardNo As String
Dim strCardEx As String
Dim intSortCode As String
Dim strDeliveryAdd As String
Dim strPostCode As String
Dim intProductID As Integer
strFirstName = tbxFirstName.Text
strLastName = tbxLastName.Text
strEmailAdd = tbxEmailAdd.Text
intCardNo = tbxCardNo.Text
strCardEx = tbxCardEx.Text
intSortCode = tbxSortCode.Text
strDeliveryAdd = tbxDeliveryAdd.Text
strPostCode = tbxPostcode.Text
intProductID = ddlProduct.SelectedValue
Dim strDatabaseNameAndLocation As String
strDatabaseNameAndLocation = Server.MapPath("KingToots.mdb")
Dim strSQLCommand As String
strSQLCommand = "INSERT INTO Customer(FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strEmailAdd & "', '" & intCardNo & "', '" & strCardEx & "', '" & intSortCode & "', '" & strDeliveryAdd & "', '" & strPostCode & "');"
Dim objOleDbConnection As System.Data.OleDb.OleDbConnection
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
Dim objOleDbCommand As System.Data.OleDb.OleDbCommand
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "INSERT INTO Orders(ProductID) " & "Values ('" & intProductID & "');"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
objOleDbCommand.ExecuteNonQuery()
objOleDbConnection.Close()
strSQLCommand = "SELECT Customer.* FROM Customer ORDER BY Customer.CustomerID DESC;"
objOleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & strDatabaseNameAndLocation)
objOleDbConnection.Open()
objOleDbCommand = New System.Data.OleDb.OleDbCommand(strSQLCommand, objOleDbConnection)
Dim objOleDbDataReader As System.Data.OleDb.OleDbDataReader
objOleDbDataReader = objOleDbCommand.ExecuteReader()
Dim datDataTable As System.Data.DataTable
datDataTable = New System.Data.DataTable()
datDataTable.Load(objOleDbDataReader)
objOleDbConnection.Close()
tbxFirstName.Text = ""
tbxLastName.Text = ""
tbxEmailAdd.Text = ""
tbxCardNo.Text = ""
tbxCardEx.Text = ""
tbxSortCode.Text = ""
tbxDeliveryAdd.Text = ""
tbxPostcode.Text = ""
End Sub
You're missing the closing quotes at the end of this line:
strSQLCommand = "INSERT INTO Customer(FirstName, LastName, EmailAdd, CardNo, CardEx, SortCode, DeliveryAdd, Postcode) " & _
"Values ('" & strFirstName & "', '" & strLastName & "', '" & strEmailAdd & "', '" & intCardNo & "', '" & strCardEx & "', '" & intSortCode & "', '" & strDeliveryAdd & "', '" & strPostCode & ");"
About the obvious SQL injection problem, switching to parameters would be the best way to do it (and you'd never have your original issue if you did, parameters don't use quotes), but at the very least run a replace on your strings to replace ' with '' so your program doesn't just die if you get a customer called O'Neil.
He is correct, you don't want to do this you will get sql injection. But here is the solution to your problem anyway.
The problem is not in the last sql statement but in the previous one.
'" & strPostCode & " is missing the last single quote.
it should read:
'" & strPostCode & "');