Reputation: 6232
I'm trying to create a "dynamic" field in my SQL query
INSERT INTO tblCARS (CreateField("[tblCARS]","[colors]","TEXT"))
SELECT avail_colors
FROM tblSHOPS
WHERE car_model = model_car;
This should give me the same result as
INSERT INTO tblCARS (colors)
SELECT avail_colors
FROM tblSHOPS
WHERE car_model = model_car;
The field [colors] does not exist, so i want to append it to the existing table called [tblCARS] when i run the query.
The function CreateField()
looks like this
Public Function CreateField(strTable As String, strField As String, strType As String) As Variant
CreateField = Null
If (strField <> vbNullString) And (DoesTblFieldExist(strTable, strField) = False) Then
CurrentDb.Execute "ALTER TABLE " & strTable & " ADD COLUMN " & strField & " " & strType
End If
CreateField = strField
End Function
When i run the query, Access gives me the error "incorrect syntax" (translated) and the cursor stops at the second parenthesis.
Have anyone succeeded with creating fields at runtime on a Access query?
I know i could do this entirely on VBA, but that is not my goal.
Any hints?
Upvotes: 1
Views: 1049
Reputation: 97101
That approach attempts to have the db engine determine the name of the destination field when the statement is executed. Unfortunately, Access' db engine does not provide that capability.
Essentially, the statement treats that CreateField()
function as a parameter. And Access won't let you use a parameter for a field name.
Consider a straightforward parameter example. This statement succeeds ...
INSERT INTO tblFoo(some_text) VALUES ("bar");
But when providing the same field name (some_text) as a parameter, the statement fails ...
PARAMETERS which_field Text ( 255 );
INSERT INTO tblFoo(which_field) VALUES ("bar");
So you'll need to use 2 operations instead of a single query. You could execute the ALTER TABLE
and then a revised INSERT
with the field name hard-coded into the statement.
Upvotes: 3