How to pass variables from VBA through SQL? [duplicate] - sql

This question already has answers here:
How do I use parameters in VBA in the different contexts in Microsoft Access?
(2 answers)
Closed 4 years ago.
I'm trying to pass values from a Form into my database, via SQL:
Private Sub Befehl4_Click()
Dim SQL As String
Dim unique As String
unique = Forms!frm_test!PN
SQL = "INSERT INTO tab_test (Feld1) VALUES (unique)"
DoCmd.RunSQL SQL
End Sub
When I execute this code from my button in my Form, unique isn't passed to the SQL-command. I have to type it in. When writing the SQL-command this way:
SQL = "INSERT INTO tab_test (Feld1) VALUES (Forms!frm_test!PN)"
It works how expected.
What am I missing or doing wrong?

SQL = "INSERT INTO tab_test (Feld1) VALUES ('" & Forms!frm_test!PN & "')"

Related

My Microsoft Access Append Query (VBA and SQL) works for a literal, but not for a variable

This is Microsoft Access, VBA and SQL related.
In VBA I make this SQL statement (see below) and run it. This correctly appends to testTable. (The field in testTable is Date/Time and it has format 'mm/dd/yyyy hh:nn:ss')
sql = "INSERT INTO testTable (DateOpen) VALUES ('12/01/2021 12:13:14')
However, when I do this (below), the code prompts me with a "Enter Parameter Value" for dateVar. Why? I just told it what dateVar was in the SQL.:
DIM dateVar as string
dateVar = "12/01/2021 12:13:14"
sql = "INSERT INTO testTable (DateOpen) VALUES (dateVar)
When I add quotes (see below) the code does not prompt me with an Enter Parameter Value msgbox.
I get a msgbox that says You Are About To Append. But when it tries to append it fails with "Microsoft Access Can't Append the Records" due to a "type conversion error"
DIM dateVar as string
dateVar = "12/01/2021 12:13:14"
sql = "INSERT INTO testTable (DateOpen) VALUES ('dateVar')
Help Please??
Your concatenation of the dateVar variable into the SQL string needs to be fixed:
Dim dateVar as string
dateVar = "12/01/2021 12:13:14"
sql = "INSERT INTO testTable (DateOpen) VALUES ('" & dateVar & "')"
If you're having problem building your SQL then Debug.Print sql will let you see what's actually getting executed.

Ms Access SQL: Concatenate seperated by commas one to many relationship [duplicate]

This question already has an answer here:
Combine values from related rows into a single concatenated string value
(1 answer)
Closed 6 years ago.
With the following kind of table:
tblRequest
-RequestID(double)
-RequestDescription (String)
tblError
-ErrorID(long integer)
-ErrorName(String)
-RequestID(double)
The above relationship is a ONE to MANY relationship.
I want to VIEW the data in the following manner. Therefore, I need a SELECT query which displays the data in the following manner.
Request Error(s)
1 Error1, Error6
2 Error2, Error3
3.4 Error4, Error2, Error1
I tried to search for an answer which involved FOR XML PATH('')). However, I do not think it can work in Ms-Access.
Here's a potential solution.
Step 1:
Create this function in your MS Access App.I don't think this is the most efficient solution, however it should work well enough if the number of records isn't very large.
Public Function getErrorText(ByVal MyId As Double) As String
Dim myrs As Recordset
'Create the recordset
Set myrs = CurrentDb.OpenRecordset("select distinct ErrorID from tblError where RequestID = " & MyId)
'Build the error string
Do Until myrs.EOF
getErrorText = myrs.Fields(0).Value & ", " & getErrorText
myrs.MoveNext
Loop
'Clean up
myrs.Close
Set myrs = Nothing
'Return the correct cleaned up string
getErrorText = Left(getErrorText, Len(getErrorText) - 2)
End Function
Step 2:
You should then be able to run the following SQL statement to get the output desired.
SELECT distinct tblError.RequestID, getErrorText( tblError.[RequestID]) AS [Error(s)]
FROM tblError INNER JOIN tblRequest ON tblError.RequestID = tblRequest.RequestID
WHERE (((getErrorText( tblError.[RequestID])) Is Not Null));

VBA Insert Into VALUES is reading null for a local variable

I am using Microsoft Access and trying to pull the ID from a table (named Hazards) that has the same ID as the one on a Form (named Edit Hazards). After I pull this value, I want to insert it into another table (named People_Hazards) under Title (Which is an ID as well due to a lookup to another table).
However after I insert it into a local variable, when I try putting it into the insert statement for VALUES, I receive the error message that there are 'Expected parameters 1'.
I have tried using a MsgBox to check if the lookup is correct, and it works fine. But when using the Insert Statement it appears to be receiving nothing for the variable.
I have also triple checked that all my Data Types are correct but even then nothing seems to be working. Any help would be very appreciated! My code is below.
Dim x
x = DLookup("[ID]", "Hazards", "[Hazards].[ID] = " & Forms![Edit Hazards]![ID])
MsgBox x 'I receive the correct value in the message box here'
CurrentDb.Execute "INSERT INTO People_Hazards([Title]) VALUES (x)"
I don't know if its a typo or not but you are inserting x as opposed to the value of x ,
I recommend making a string first and try to use CurrentDb.Execute on it
Dim strSql as string
Dim x as String
x = DLookup("[ID]", "Hazards", "[Hazards].[ID] = " & Forms![Edit Hazards]![ID])
strSql="Insert into People_Hazards([Title]) VALUES ("& x & ")"
Msgbox(strSql)
CurrentDb.Execute strSql

Unable to insert string into Access database

I am using a WPF application to insert a student into my MS Access database.
I wanted to use a parameter with this code:
Dim sql As String = _
"INSERT INTO exams " & _
"VALUES (#student)"
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
opdracht.Parameters.Add(New OleDbParameter("#student", 5))
but this doesn't work.
The only way i get it to work is this one:
Dim sql As String = _
"INSERT INTO exams " & _
"VALUES (" & student & ")"
' opdracht initialiseren
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
To use this query I use the command, this is the point where I get my error.
opdracht.executeNonQuerry()
The table layout in MS Access looks like this:
And my application inserts the other values corectly but i left them out to keep a minimal example.
If you have a variable named student and you want to use its value for the parameter then you need to assign that variable as parameter's value
Dim sql As String = "INSERT INTO exams VALUES (#student)"
Dim opdracht As OleDbCommand = New OleDbCommand(sql, connectie)
opdracht.Parameters.AddWithValue("#student", student)
opdracht.ExecuteNonQuery()
Of course, I am assuming this because you say that the string concatenation version is working, and in that example you concatenate the value of a variable named student in your command text
Remember that with OleDb the name of your parameters is meaningless because OleDb use the position of the placeholder to pass the parameters' values, not the parameter name
EDIT Using INSERT INTO without specifying the column names works only if you add the parameters for all fields. Your database table contains other fields so you need to specify them or use a different syntax for the INSERT INTO
Dim sql As String = "INSERT INTO exams (Student) VALUES (#student)"
But this will fail also because you have the Student field part of your primary key. The fields that belong to a Primary Key cannot be null so you have no choice but add all the values required by the primary key
Dim sql As String = "INSERT INTO exams (Student, locaal, opleidingsOnderdeel) " & _
"VALUES (#student, #local, #oplei)"
.. add the parameter's value for student, local and oplei
However, I am a bit perplexed that the string concatenation works. What is the value of the variable student? You should get the same error as using the parameterized query with only one parameter.

Insert Excel Cell values into an existing SQL table [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Excel VBA INSERT INTO statement using variables
I've just started learning a bit of VBA, I've managed to import data from a DB created in SQL Server just fine, now I'm trying to export data from Excel into the same DB.
The following works just fine:
Dim cnState As ADODB.Connection
Dim sSQL As String
Set cnState = New Connection
With cnState
.Provider = "SQLOLEDB"
.ConnectionString = "server=.\SQLEXPRESS; Trusted_Connection=Yes; database=SIM_PROJ"
.Open
End With
sSQL = "Insert Into Alunos Values ('3', 'Tiago Aleixo', 'Rua dos Pincéis' , '1990-05-26' , 'M' , 'Multimédia' , 'D')"
cnState.Execute sSQL
End Sub
Private Sub btn_goMenu_Click()
Sheet1.Select
The only issue is, I've only managed to figure out how to insert actual values through the code, I want to be able to read a whole line in Excel and insert it into my DB.
Something like this:
sSQL = "Insert Into Alunos Values (Range(A4).Value, Range(B4).Value, Range(C4).Value, Range(D4).Value, Range(E4).Value, Range(F4).Value, Range(G4).Value)"
IE, I only want values from line 4 to be inserted.
Probably you have to build the string more incrementally like:
SQL = "INSERT INTO alunos VALUES ('" + Range(A4).Value + "', '" + Range(A5).Value + "', '"...
The syntax you show looks ilke it would try to insert the string "Range(A4).Value" into the database.
Save your file as comma delimited CSV file and then you can use bulk insert as below.
declare #sql varchar(max)
set #sql = "BULK INSERT Alunos FROM '"+#File+"' WITH (FIELDTERMINATOR = ',') "
exec (#sql)