why the following msaccess vba statement fails when add the where statement?
I want to check if the field has value
Set rsMySet = CurrentDb.OpenRecordset("PivotTblInvDepts")
'Start the count at the position number of the first column-oriented field
'Remember that Recordsets start at 0
For i = 3 To rsMySet.Fields.Count - 1
'*********************************************************************************************************************
'Use the recordset field.name property to build out the SQL string for the current field
strSQL = "INSERT INTO TabularDepts ([Depts], [Code], [Description], [Qty])" & _
"SELECT" & "'" & rsMySet.Fields(i).Name & "'" & " AS Dept," & _
"[PivotTblInvDepts].[Code],[PivotTblInvDepts].[Description]," & _
"[" & rsMySet.Fields(i).Name & "]" & _
"FROM PivotTblInvDepts;" & _
"WHERE" & " (rsMySet.Fields(i).Name)>0"
Try removing the ; in FROM PivotTblInvDepts;.
Also you need space at the end of the previous line. "[" & rsMySet.Fields(i).Name & "]" & _ should be "[" & rsMySet.Fields(i).Name & "] " & _. Likewise, make sure to add a space so that you do no result in FROM PivotTblInvDeptsWHERE
Your current SQL reads something like this
INSERT INTO TabularDepts ([Depts], [Code], [Description], [Qty])
SELECT '<data>' As Dept,
[PivotTblInvDepts].[Code],[PivotTblInvDepts].[Description],
[<data>]
FROM PivotTblInvDepts;
WHERE <condition>
After removing the ;, the insert will be cleaner.
Related
I'm running an SQL query through VB in Microsoft Access for form to add records to a table. However, it keeps asking me to insert parameter value, when they are already present in the form.
Private Sub AddPart_Click()
Dim strSQL As String
strSQL = "INSERT INTO Part VALUES (" & Me.IdPartPrimary.Value & ", " & Me.NamePartPrimary.Value & ", " & Me.BrandPartPrimary.Value & ", " & Me.ModelPartPrimary.Value & ", " & Me.FunctionPartPrimary.Value & ", -1, " & Me.FatherPartPrimary.Value & ", " & Me.ProviderPartPrimary.Value & ", " & Me.AmountPartPrimary.Value & ");"
DoCmd.RunSQL strSQL
End Sub
I already checked for spelling mistakes and there were none. Also, this happens with every field. If I don't insert a parameter value and cancel instead, the record still gets added, only after I close and reopen the table lots of times.
If fields are text type, need text delimiters - apostrophe will serve. I assume comboboxes have a number value from a hidden foreign key column. Value property does not need to be specified as it is the default.
With Me
strSQL = "INSERT INTO Part " & _
" VALUES (" & .IdPartPrimary & ", '" & _
.NamePartPrimary & "', '" & .BrandPartPrimary & "', '" & _
.ModelPartPrimary & "', '" & .FunctionPartPrimary & "', -1, " & _
.FatherPartPrimary & ", " & .ProviderPartPrimary & ", " & .AmountPartPrimary & ")"
End With
AFAIK, Access cannot execute multi-action SQL statements but SQL injection is still possible. If you want to explore use of Parameters in VBA, review How do I use parameters in VBA in the different contexts in Microsoft Access?
Another alternative to avoid SQL injection is to open a recordset, use its AddNew method to create a new record, and set value of each field. DAO.Recordset AddNew
Code
strSQL = "SELECT tblHS_area_fields.hsaf_id " _
& "FROM tblHS_area_fields " _
& "WHERE (((tblHS_area_fields.hs_area_id)=" & hs_area_id & ") AND ((tblHS_area_fields.hsf_id)=13))"
Set rs = db.OpenRecordset(strSQL)
Errors
The error when trying to run from a Form is:
Extra ) in query expression '(((tblHS_area_fields.hs_area_id)=" &
> hs_area_id & ") AND ((tblHS_area_fields.hsf_id)=13))'
Getting an error from immediate window:
Compile error: expected: line number or label or statement or end of statement
All fields are numbers.
What is wrong with the VBA code and SQL statement?
Just remove all brackets in your sql:
strSQL = "SELECT tblHS_area_fields.hsaf_id " & _
"FROM tblHS_area_fields " & _
"WHERE tblHS_area_fields.hs_area_id = " & hs_area_id & " AND tblHS_area_fields.hsf_id = 13 "
In this case you don't need the brackets.
Not an answer, but too long for a comment:
Next time, add a Debug.Print strSql, then create a query in SQL view, copy you SQL statement from the debug window (ctrl+G) and paste you statement there.
Or just paste it in Visual Studio...
You should then quickly see the issue(s)
Consider to debug-print and log your SQL before executing: Debug.print(strSQL).
Opening brackets must match closing ones
Some break-down helps recognizing and matching, correct is:
strSQL = "SELECT hsaf_id" _
& " FROM tblHS_area_fields" _
& " WHERE (" _
& "( hs_area_id =" & hs_area_id & ")" _
& " AND ( hsf_id = 13 )" _
& ")"
For SQL templates you could also use string replace function or string-templating with a custom-function. See VBA string interpolation syntax.
I'm running an Insert Into SQL query from VBA, and I recently came across the string 'Women's Health / Sexual Health', which contains the ' character, and thus the query failed because ' is a text delimiter. This is how I get the text for the query:
Function getSqlInsertIntoQuery(arrHeaders, arrValues, tableIndex As enumTables)
Dim dHeadersAndValues As New scripting.Dictionary
Dim TableName As String
TableName = getTableName(tableIndex)
getSqlInsertIntoQuery = "INSERT INTO " & TableName & " ( [" & _
Join(arrHeaders, "]," & vbNewLine & "[") & "])" & _
" VALUES( " & Chr(39) & Join(arrValues, Chr(39) & "," & Chr(39)) & Chr(39) & ") ;"
Debug.Print getSqlInsertIntoQuery
End Function
Can anyone tell me of a way to clean the text of special characters that I should escape? Or is there a list of characters that I can replace using regex?
I made a SQL statement in the add/update button in the query wizard I changed it back to SQL view to see how the program made me the code and when I copy and paste the same error on the If statement of the btnAdd it throws me a syntax error, but how?
here is the entire code:
Private Sub cmdAdd_Click()
'In the button add we have two options
'1. Insert
'2. Update
If Me.txtID.Tag & "" = "" Then
CurrentDb.Execute "INSERT INTO tblClients ( ClientID, ClientName, Gender, " & _
"City, [Address (Fisical)], [Cellphone/Telephone] ) " & _
"SELECT " & Me.txtID & ",'" & Me.txtName & "','" & Me.cboGender & "', '" & Me.cboCity & "','" & Me.txtAddress & "','" & Me.txtCellphone & "'"
Else
'Otherwise the data will be updated
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] "
WHERE (([ClientID]=[Me].[txtID].[Tag]));
End If
cmdClear_Click
tblClients_subform.Form.Requery
End Sub
it highlights me this row in red:
WHERE (([ClientID]=[Me].[txtID].[Tag]));
It appears that the following code is not on the same line
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] "
WHERE (([ClientID]=[Me].[txtID].[Tag]))
So you may want to change it to
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] " & _
"WHERE (([ClientID]=[Me].[txtID].[Tag]))"
In addition to Cableload's correct answer where the WHERE statement that was on a new code line was not connected to the previous line by the use of an underscore at the end of the first one, there is still a referncing issue.
You are referencing values in a UserForm like that were columns in a table so it is not finding the value you are looking for. To get the value into the SQL statement you need to come out of the literal string, reference the value, and then continue writing the string (not forgetting to enclose the value with '): -
CurrentDb.Execute "UPDATE tblClients SET " & _
"[ClientName] = '" & Me.txtName & "', " & _
"[Gender] = '" & Me.cboGender & "', " & _
"[City] = '" & Me.cboCity & "', " & _
"[Address (Fisical)] = '" & Me.txtAddress & "', " & _
"[Cellphone/Telephone] = '" & Me.txtCellphone & "' " & _
"WHERE [ClientID]=" & Me.txtID.Tag
I have spread it across multiple lines for ease of reading but obviously you can adjust your actual code however needed.
I would also question [ClientID]=" & Me.txtID.Tag, is the ClientID in the in the txtID.value or the txtID.Tag, they are different places. The value property is the value in the text box, the Tag property is more like a area for metadata that you can populate if needed but is not automatically populated by default.
Finally I'd like to refer you back to an answer to a previous question you had, at the bottom of the answer there was a tip about placing the resultant query into a Access Query in SQL view to get better information on the error, that would have helped you here too. To give further assistance on the 'resultant query'.
In debug mode before the while the CurrentDb.Execute is highlighted but before it is run (using F8 to step through each line until you get there, or placing a breakpoint on that line
Open the the Immediate Window if it is not already open (either Ctrl+G to from the menu bar 'View' > 'Immediate Window')
Copy all related code from the line after the CurrentDb.Execute statement, in this case it would be UPDATE ... .Tag
In the immediate window type a question mark and then paste in the rleated code and press enter
The immediate window will return the resultant string for you to try in a Query in SQL view.
Change the SELECT keyword to VALUES in your INSERT statement.
CurrentDb.Execute "INSERT INTO tblClients ( ClientID, ClientName, Gender, " & _
"City, [Address (Fisical)], [Cellphone/Telephone] ) " & _
"VALUES (" & Me.txtID & ",'" & Me.txtName & "','" & Me.cboGender & "', '" & Me.cboCity & "','" & Me.txtAddress & "','" & Me.txtCellphone & "')"
And the UPDATE should be this. The issue here was that you were trying to use Form controls in the SQL, but you needed to evaluate the controls first then concatenate their values to your literal string.
I'm wondering if you really need Me.txtID instead of Me.txtID.Tag
So sway that out if it doesn't work.
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = '" & me.txtName & "', tblClients.Gender = '" & me.cboGender & "', tblClients.City = '" & me.cboCity & "', tblClients.[Address (Fisical)] = '" & me.txtAddress & "', tblClients.[Cellphone/Telephone] = '" & me.txtCellphone & "' WHERE (([ClientID]=" & Me.txtID.Tag & "));"
So I'm trying to insert 120 rows into a new table and it keeps throwing "Query too complex" errors at me. It works fine upto 90 rows.
This is the query:
SQL = "INSERT INTO " & newtable & " ([" & sourceQ & "_" & master & "],
[" & sourceQ & "_" & fld.Name & "])" & " SELECT
[" & sourceQ & "." & master & "], [" & sourceQ & "." & fld.Name & "]"
& " FROM " & sourceQ
I have tried playing with where clauses adding WHERE [" & sourceQ & ".Expr1] like ('Field09?') but it still throws those errors.
I even tried a simple one that should work like WHERE [" & sourceQ & ".Expr1] = 'Field001', which should just be 1 row, but it still throws the error.
Anyone have any ideas?
edit: debug
INSERT INTO tblCalc ([qJoinKeyAndStudent_<>], [qJoinKeyAndStudent_0 1 0 1])
SELECT [qJoinKeyAndStudent.<>], [qJoinKeyAndStudent.0 1 0 1]
FROM qJoinKeyAndStudent WHERE [qJoinKeyAndStudent.Expr1] like ('*09#')
While Access is capable of handling spaces in field and table names, you need to encapsulate both the field and table names in separate brackets:
INSERT INTO tblCalc ([qJoinKeyAndStudent_<>], [qJoinKeyAndStudent_0 1 0 1])
SELECT [qJoinKeyAndStudent].[<>], [qJoinKeyAndStudent].[0 1 0 1]
FROM qJoinKeyAndStudent WHERE [qJoinKeyAndStudent].[Expr1] like ('*09#')
Does that work?