SQL code in VB MS Access inserts the new records to the middle of the table, not at the botom - ms-access

In MS Access, I need to insert new records using SQL code.
I wrote the following code in VB and it inserts the code to the middle of the table.
Is there any chance to find out the reason?
sql = "INSERT INTO Audit_riskModelHistory (Action, User, modelKey, modelEventKey) " & _
"VALUES ('New Record Inserted', 'Mike-Admin', " & _
Me.cmb1.Value & ", " & Me.cmb2.Value & ")"
DoCmd.SetWarnings False
DoCmd.RunSQL (sql)
DoCmd.SetWarnings True
I tried looking at the properties of the table but I did not find the reason.

Related

How do I re-define the SQL in a QueryDef? I have code that works by deleting and re-creating the QueryDef, but I can't get the overwrite to work

I am told (and agree) that it is better to replace the SQL in an existing querydef, rather than delete and re-define the querydef each time the query needs to change. But my code only seems to work the second way. Here is the code I have that works:
Dim db As Database
Set db = CurrentDb
Dim QD As QueryDef
Dim mySql As String
mySql = ""
mySql = "TRANSFORM COUNT(tblDocs.Document) AS CountOfDocument " & _
"SELECT tblDocs.[Contractor Dept], " & _
"COUNT(tblDocs.Document) AS [Total Of Document] " & _
"FROM tblDocs " & _
"GROUP BY tblDocs.[Contractor Dept] " & _
"PIVOT tblDocs.[Engineering Status Code]"
On Error Resume Next
db.QueryDefs.Delete "qryX" 'Remove temporary query if exists
Set QD = db.CreateQueryDef("qryX", mySql) 'create temporary query
DoCmd.RunSQL "SELECT * INTO tblDocsCrossTabX FROM qryX;"
Here is the code I can't get to work
Dim db As Database
Set db = CurrentDb
Dim QD As QueryDef
Dim mySql As String
mySql = " "
Set QD = db.CreateQueryDef(("qryX"), mySql)
mySql = "TRANSFORM COUNT(tblDocs.Document) AS CountOfDocument " & _
"SELECT tblDocs.[Contractor Dept], " & _
"COUNT(tblDocs.Document) AS [Total Of Document] " & _
"FROM tblDocs " & _
"GROUP BY tblDocs.[Contractor Dept] " & _
"PIVOT tblDocs.[Engineering Status Code]"
QD.SQL = mySQL 'overwrite query SQL
DoCmd.RunSQL "SELECT * INTO tblDocsCrossTabX FROM qryX;"
Oddly, the second version doesn't throw any errors at me, but it doesn't make the crosstab table at all.
Edit: Maybe I wasn't clear enough. The problem is that the second set of code Does. Not. Execute. The. SQL. If it executed the code, I would be happy to re-write and use the same temp query over and over, but it does. not. execute. the. SQL..
Please respond with how to make the code in the second block actually execute the indicated SQL statement and build the desired table.
I know I have to remake a query if I delete it. Duh.
I know I "should" be able to re-use the same query if I can get the Set statement to properly overwrite the previous sql with the desired sql.
I know you all want to provide an answer, but please make it an answer to the question I am asking.
You can recycle the object if you don't delete it:
' On Error Resume Next
Set QD = db.QueryDefs("qryX")
QD.SQL = mySQL
DoCmd.RunSQL "SELECT * INTO tblDocsCrossTabX FROM qryX;"
Solved.
In the first block of code, when I delete and recreate the query, the string mySql contains a valid SQL statement, so Access is able to assign that SQL to the querydef when I completely recreate it with SET. Specifically,
mySql = "Transform..."
Comes Before
Set QD = db.CreateQueryDef("qryX", mySql)
In the second set of code, the string mySql contains only a space when the Set command is used, as " " is not a valid SQL Statement, the Set command won't even get executed, and the QueryDef QD never even gets created.
Specifically, the error in the second code occurs because
mySql = " " 'NOT a valid SQL Statement
comes before the attempt to create the queryDef
Set QD = db.CreateQueryDef(("qryX"), mySql) 'QD never gets created because mySql is not valid SQL
preventing the assignment of a valid SQL statement later, and so no table gets created.
If you can use a subquery, you can use a tempory QueryDef instead of bothering with checking forQueryDefalready existing or not, just combine the SELECT and the INSERT-Query to use a temporaryQueryDef
Unfortunally you can't useTransformin a subquery so this code leads toRuntime-Error 3129 Invalid SQL statement.
Sql = "SELECT * INTO tblDocsCrossTabX FROM (TRANSFORM COUNT(tblDocs.Document) AS CountOfDocument " & _
"SELECT tblDocs.[Contractor Dept], " & _
"COUNT(tblDocs.Document) AS [Total Of Document] " & _
"FROM tblDocs " & _
"GROUP BY tblDocs.[Contractor Dept] " & _
"PIVOT tblDocs.[Engineering Status Code])"
With CurrentDb.CreateQueryDef(vbNullString) 'or db.CreateQueryDef("") creates a not named and therefore temporary QueryDef
.SQL = Sql
.Execute dbFailOnError
End With
Sample of successful code.
Dim db As Database
Set db = CurrentDb
Dim QueryString As String
Dim QDDocsCross As QueryDef
Set QDDocsCross = db.CreateQueryDef("DocsCross")
QueryString = "TRANSFORM COUNT(Docs.Document) AS CountOfDocument " & _
"SELECT Docs.[Contractor Dept], " & _
"COUNT(Docs.Document) AS [Total Of Document] " & _
"FROM Docs " & _
"GROUP BY Docs.[Contractor Dept] " & _
"PIVOT Docs.[Engineering Status Code]"
QDDocsCross.SQL = QueryString

What's wrong with this SQL code? (VBA MS Access)

insertString = "INSERT INTO paymentRecord(paymentEventDate,paymentType,paymentRecordNotes,value,clientID,jobID)
VALUES (recordDate,recordType,recordNotes,paymentValue,clientID,jobID);"
DoCmd.SetWarnings False
DoCmd.RunSQL insertString
DoCmd.SetWarnings True
This code returns a syntax error and I don't know why. All insert values and columns are correct.
The code is being used in a MS Access front-end with a MySQL database back-end.
You must concatenate the values:
" .. VALUES (" & recordDate & "," & recordType & "," & recordNotes & "," & paymentValue & "," & clientID & "," & jobID)"
Also, the values must be formatted and delimited correctly, for example by using my function CSql.
Even better, use parameters.

Running an SQL string in VBA?

Iv created the SQL string sql in ms access vba but when it runs it prints the string in the debug window but doesn't actually run the string to add a record to the table like I want it to.
Public Sub EmpoyeesTable_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24);"
Debug.Print sql
End Sub
Ultimately I want to use SQL strings to take input from a form when submit is clicked and add it to a table? Is this even the right approach?
There are many ways to run SQL strings in VBA. Each have their own advantages, and disadvantages. The most common ones are:
DoCmd.RunSQL sql
Runs the SQL just as it would if you executed a query. Popup will occur when you add, delete or modify records. You can use UDFs and form parameters
DoCmd.SetWarnings False
DoCmd.RunSQL sql
DoCmd.SetWarnings True
Disables warnings, then runs the SQL like in the previous way, then sets warnings back on.
CurrentDb.Execute sql
Executes the SQL over a DAO connection to the current database. You can't use UDFs and form parameters here. No warnings are shown. It just executes the SQL.
CurrentProject.Connection.Execute sql
Executes the SQL over an ADO connection to the current database. Very similar to the DAO connection, but there are subtle differences. For example, you can execute DDL statements that contain the Decimal data type, and set Check constraints in this way, while both are not allowed in any of the other ways.
You can read about using parameters with these different ways here. That's strongly recommended if you are going to insert values that aren't constant, to avoid bugs and SQL injection.
If you think simply then just change your Debug.Print sql to DoCmd.RunSQL (sql)
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24)"
DoCmd.RunSQL (sql)
End Sub
If you want take values from form then refer each value from form control like text box. See the below codes.
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees VALUES (" & _
"'" & Me.Text1 & "'," & _
"'" & Me.Text2 & "'," & _
"'" & Me.Text3 & "'," & _
"'" & Me.Text4 & "'," & _
"'" & Me.Text5 & "'," & _
"'" & Me.Text6 & "');"
DoCmd.RunSQL (sql)
End Sub
If the field value is number type the you can remove singe quote (') from code for those field.

currentdb execute does not insert

I'm having trouble with Access VBA. I made the following code to insert some data to my SQL DB.
Private Sub btnFilmKijkenKlant_Click()
CurrentDb.Execute "INSERT INTO watchhistory (movie_id, customer_mail_address, watch_date, price, invoiced) VALUES (" & movie_id.Value & ", '" & Me.txtEmail & "', Date(),'" & price.Value & "', '0')"
End Sub
When the user hits the button I want some data to be transferred to the DB.
I don't get any errors but it just doesn't insert...
I made txtEmail field for testing. I got an e-mail field in another form that I want to use as customer_mail_address.
When I include the dbFailOnError option with CurrentDb.Execute, Access complains "ODBC Call failed", but I don't understand why.
Dim db as Database
Set db = CurrentDb()
db.execute(......)

saving data from form to table in access

I have a form, and I want to fill it, and then save some of the fields into an existing table called Order.
I'm trying to do this with this line of code:
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES (' " & Me.order & " ')"
I have also tried it like this
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES ( " & Me.order & " )"
but it doesn't seem to make a difference. I keep getting the following error:
run-time error '3134': syntax error in INSERT INTO statement.
what am I doing wrong?
Order is a reserved word. If you must keep that as the table name, bracket it to avoid confusing the db engine.
Dim strInsert As String
strInsert = "INSERT INTO [Order] (OrderNumber) VALUES ('" & Me.order & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailOnError
If OrderNumber is numeric data type instead of text, discard those single quotes from the INSERT statement.
Store your statement in a string variable. Then use Debug.Print to examine the completed statement you're asking the engine to execute. You can view the Debug.Print output in the Immediate window. Go there with Ctrl+g Copy the statement and paste it into SQL View of a new Access query for troubleshooting.