Query causes UPDATE syntax error, when 'where-attribute' is a date - vba

Whenever i try to update a table in the SQL-Database via excel-vba using a Date-formated primary key as the
'where-attribute', a syntax error appears while executing the SQLQuery; in my example: wrong syntax near ".1900".
However, when i create a table in sql using the 1900er number-format to express dates(as excel saves dates: 1 = 01.01.1900; 2 = 02.01.1900 etc.), format the date-column according to that in my excel-sheet, which shall be used to update the table in SQL, and run the exact same code, no error appears and the SQL-table gets updated. Here is an extract of my used code.
strWhere = "[Date] = " & strDate
SQLQuery = "update " & TableNameSql & " " & _
"set " & _
"[Column1Data] = '" & strColumn1Data & "' " & _
"Where " & strWhere
the debug.print of the SQLQuery for both options look as following:
update TableNameSql set [Column1Data] = '-0,1149' Where [Date] = 02.01.1900 'Error
update TableNameSql set [Column1Data] = '-0,1149' Where [Date] = 2 'no Error
I believe it may have to do with the dots in the date(strWhere).
It could also be, that the Problem accurs because of different language settings in excel and SQL-Server. However, creating tables and exporting data from SQL to Excel is no Problem.
I've found different similar questions asked, however, none of the answers suited my specific problem.
Using the 1900er-Date-Format is also not useful in practice, so i would like to get this error fixed while using regular dates.

Consider using the ISO date format as YYYY-MM-DD which you can format using VBA's Format() assuming strDate is a VBA Date type. Also, be sure to enclose in single quotes.
strWhere = "[Date] = '" & Format(strDate, "YYYY-MM-DD") & "'"
Even better consider parameterization and avoid any quotation or concatention such as ADO command which allows you to align data types:
' PREPARED STATEMENT WITH QMARKS
SQLQuery = "UPDATE " & TableNameSql & " " & _
"SET [Column1Data] = ? " & _
"WHERE [Date] = ?"
' ... LOAD ADO CONNECTION ...
Set cmd = New ADODB.Command
With cmd
.Activeconnection= conn
.CommandText = SQLQuery
.commandType = adCmdText
' BIND PARAMS
.Parameters.Append .CreateParameter("StrParam", adVarChar, adParamInput, 255, strColumn1Data)
.Parameters.Append .CreateParameter("DateParam", adDate, adParamInput, , strDate)
' RUN ACTION QUERY
.Execute()
End With

Related

Microsoft Access VBA code with Select SQL String and Where clause

I'm using Microsoft Access to develop a database app. An important feature the user would need is to automatically send an email update to all relevant stakeholders.
The problem is that I'm getting
Run-time error '3075' Syntax error in query expression.
Here it is below:
Set rs = db.OpenRecordset("SELECT StakeholderRegister.[StakeholderID], StakeholderRegister.[ProjectID], StakeholderRegister.[FirstName], StakeholderRegister.[LastName], StakeholderRegister.[EmailAddress] " & _
" FROM StakeholderRegister " & _
" WHERE (((StakeholderRegister.[ProjectID]=[Forms]![ChangeLog]![cboProjectID.Value])) ;")
Funny thing is that I created a query table on Access to create the relevant recordset and the turned on SQL view to copy the exact sql string that's above. That query works however it opens an Input Parameter box, whereas this code should be using the value typed into a forms text box as a matching criteria.
To use a variable as a parameter, do not include it within the quotes:
" WHERE StakeholderRegister.[ProjectID]=" & [Forms]![ChangeLog]![cboProjectID].[Value]
or just
" WHERE StakeholderRegister.ProjectID=" & Forms!ChangeLog!cboProjectID.Value
Note: You really only need the square brackets when there is something like a space in the name, which is not the best practice anyway.
I also took the liberty to remove the parentheses, as they are not needed in such a simple WHERE clause, and can cause more trouble than they are worth.
Try,
Dim strSQL As String
strSQL = "SELECT StakeholderRegister.[StakeholderID], StakeholderRegister.[ProjectID], StakeholderRegister.[FirstName], StakeholderRegister.[LastName], StakeholderRegister.[EmailAddress] " & _
" FROM StakeholderRegister " & _
" WHERE StakeholderRegister.[ProjectID]=" & [Forms]![ChangeLog]![cboProjectID].Value & " ;"
Set rs = Db.OpenRecordset(strSQL)
if [ProjectID] field type is text then
Dim strSQL As String
strSQL = "SELECT StakeholderRegister.[StakeholderID], StakeholderRegister.[ProjectID], StakeholderRegister.[FirstName], StakeholderRegister.[LastName], StakeholderRegister.[EmailAddress] " & _
" FROM StakeholderRegister " & _
" WHERE StakeholderRegister.[ProjectID]='" & [Forms]![ChangeLog]![cboProjectID].Value & "' ;"
Set rs = Db.OpenRecordset(strSQL)

Run Time error 3061 Too Few parameters. Expected 6. Unable to update table from listbox

All,
I am running the below SQL and I keep getting error 3061. Thank you all for the wonderful help! I've been trying to teach myself and I am 10 days in and oh my I am in for a treat!
Private Sub b_Update_Click()
Dim db As DAO.Database
Set db = CurrentDb
strSQL = "UPDATE Main" _
& " SET t_Name = Me.txt_Name, t_Date = Me.txt_Date, t_ContactID = Me.txt_Contact, t_Score = Me.txt_Score, t_Comments = Me.txt_Comments" _
& " WHERE RecordID = Me.lbl_RecordID.Caption"
CurrentDb.Execute strSQL
I am not sure but, you can try somethink like that
if you knom the new value to insert in the database try with a syntax like this one
UPDATE table
SET Users.name = 'NewName',
Users.address = 'MyNewAdresse'
WHERE Users.id_User = 10;
Now, if you want to use a form (php)
You have to use this
if(isset($_REQUEST["id_user" ])) {$id_user = $_REQUEST["id_user" ];}
else {$id_user = "" ;}
if(isset($_REQUEST["name" ])) {$name= $_REQUEST["name" ];}
else {$name = "" ;}
if(isset($_REQUEST["address" ])) {$address= $_REQUEST["adress" ];}
else {$adress= "" ;}
if you use mysql
UPDATE table
SET Users.name = '$name',
Users.address = '$adress'
WHERE Users.id_User = 10;
i don't know VBA but I will try to help you
Going on from my comment, you first need to declare strSQL as a string variable.
Where your error expects 6 values and access doesn't know what they are. This is because form objects need to be outside the quotations of the SQL query, otherwise (as in this case) it will think they are variables and obviously undefined. The 6 expected are the 5 form fields plus 'strSQL'.
Private Sub b_Update_Click()
Dim db As DAO.Database
dim strSQL as string
Set db = CurrentDb
strSQL = "UPDATE Main" & _
" SET t_Name = '" & Me.txt_Name & "'," & _
" t_Date =#" & Me.txt_Date & "#," & _
" t_ContactID =" & Me.txt_Contact & "," & _
" t_Score =" & Me.txt_Score & "," & _
" t_Comments = '" & Me.txt_Comments & "'," & _
" WHERE RecordID = '" & Me.lbl_RecordID.Caption & "';"
CurrentDb.Execute strSQL
end sub
Note how I have used double quotes to put the form fields outside of the query string so access knows they aren't variables.
If your field is a string, it needs encapsulating in single quotes like so 'string'. If you have a date field it needs encapsulating in number signs like so #date# and numbers/integers don't need encapsulating.
Look at the code I have done and you can see I have used these single quotes and number signs to encapsulate certain fields. I guessed based on the names of the fields like ID's as numbers. I may have got some wrong so alter where applicable... Or comment and I will correct my answer.

ACCESS/SQL - Too Few Parameters

I am using the code below to create a new record in the "transactions table" the second line of the insert statement is throwing an error: Too few parameters. I have double checked and all of the field names are correct. What else could cause this type of error?
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = CurrentDb
Dim vblCustomerID As String
Dim vblMealType As String
Dim Charge As Currency
Dim vblDate As String
vblDate = Format(Date, "yyyy-mm-dd")
txtCustomerID.SetFocus
vblCustomerID = txtCustomerID.Text
txtMealType.SetFocus
vblMealType = txtMealType.Text
txtCharge.SetFocus
vblCharge = txtCharge.Text
dbs.Execute "INSERT INTO dbo_Transactions" _
& "(CustomerID, MealID, TransactionAmount, TransactionDate) VALUES " _
& "(" & vblCustomerID & ", " & vblMealType & ", " & vblCharge & ", " & vblDate & ");"
dbs.Close
As others have suggested, using a parameterized query is a much better way of doing what you're attempting to do. Try something like this:
Dim qdf As DAO.QueryDef
Set qdf = dbs.CreateQueryDef("", _
"PARAMETERS prmCustomerID Long, prmMealID Long, prmTransactionAmount Currency, prmTransactionDate DateTime;" & _
"INSERT INTO dbo_Transactions (CustomerID, MealID, TransactionAmount, TransactionDate) " & _
"VALUES ([prmCustomerID], [prmMealID], [prmTransactionAmount], [prmTransactionDate]) ")
qdf!prmCustomerID = txtCustomerID.Value
qdf!prmMealID = txtMealType.Value
qdf!prmTransactionAmount = txtCharge.Value
qdf!prmTransactionDate = Date()
qdf.Execute dbFailOnError
Set qdf = nothing
Do any of the text fields you're loading into your vbl fields contain special characters like these?
, ' "
All of those in a text field in a perfectly good SQL Insert command could screw things up, I bet that's what happening here.
It would be better if you actually use parameters here to, rather than loading the text in textboxes directly into your SQL queries, since you're opening yourself up to SQL Injections. What if someone types
"; Drop Table dbo_Transactions;
in one of your textboxes and you run this query? Your database is then totally screwed up because someone just deleted one of your tables.
A few links to info on using Parameters to prevent this issue, which I'll bet will also fix the too few parameters issue you're having.
http://forums.asp.net/t/886691.aspx
http://sqlmag.com/blog/t-sql-parameters-and-variables-basics-and-best-practices

VBA Wait for DoCmd.RunSQL OR Better Query - Ms Access

I have a query which uses an array of tables (stored as a string array) to loop through my tables and perform a Delete/Update set of queries. The queries are identical other than the table names, hence using a loop to iterate through using the table name as a variable.
The problem is, my Delete query locks the table and the Update query runs too quickly afterward; I get a "db is locked" error.
I need either of two things:
A way to tell VBA to "wait for previous command" OR
A way to concatenate these queries into one (or two) queries: one to delete the database rows and another to import the new ones. With this I could just run the queries from a standard access query (which should allocate proper time, finish queries etc)
The only catch to this is that there are parent-child relations, so the parent table has to be updated before its children (currently accomplished through array ordering).
Here's the current code which (sometimes) produces the "DB locked/in use" message:
For i = 0 To UBound(tables)
'Delete all data first
sql = "DELETE * FROM " & tables(i)
DoCmd.RunSQL sql
'Update all data second
sql = "INSERT INTO " & tables(i) & " IN """ & toDB & """ SELECT " & tables(i) & " .* FROM " & tables(i) & " IN """ & fromDB & """;"
DoCmd.RunSQL sql
Next
Should clarify: the queries take one backend's (fromDB) rows from identical tables and pushes it to another backend's (toDB) rows
EDIT: In response to the questions regarding INSERT INTO, my problem with that is if I add fields to the toDB, it will delete them if I overwrite. The reason I have to do this backdoor approach is because the database is still in development, but is also being used with select tables. Updates and feature improvements are done daily. I cannot use a simple split-backend either, because the other computer accessing the database is not always on the network (we have to manually sync it when it returns to the network), so I work on one backend and it works on another, identical(ish, minus my schema update) backend.
You can use ADO instead of DoCmd.RunSQL to execute your SQL synchronously.
Dim cmd As ADODB.Command
Dim cnn As New ADODB.Connection
Set cnn = CurrentProject.Connection
For i = 0 To UBound(tables)
Set cmd = New ADODB.Command
With cmd
.CommandType = adCmdText
.ActiveConnection = cnn
.CommandText = "DELETE * FROM " & tables(i)
.Execute
End With
Set cmd = New ADODB.Command
With cmd
.CommandType = adCmdText
.ActiveConnection = cnn
.CommandText = "INSERT INTO " & tables(i) & " IN """ & toDB & """ SELECT " & tables(i) & " .* FROM " & tables(i) & " IN """ & fromDB & """;"
.Execute
End With
Next
You could also add cnn.BeginTrans and cnn.CommitTrans to make the two statements Atomic.
Try something like this (Note I've commented your DoCmd.RunSQL. I changed it with db.Execute:
Sub DeleteInsertData(tables() As String, toDB As String, fromDB As String)
Dim db As DAO.Database
Dim i As Integer
Dim SQL As String
Set db = CurrentDb()
For i = 0 To UBound(tables)
'Delete all data first
SQL = "DELETE * FROM " & tables(i)
db.Execute SQL, dbFailOnError
'DoCmd.RunSQL SQL
'Update all data second
SQL = "INSERT INTO " & tables(i) & " IN """ & toDB & """ SELECT " & tables(i) & " .* FROM " & tables(i) & " IN """ & fromDB & """;"
db.Execute SQL, dbFailOnError
'DoCmd.RunSQL SQL
Next
Set db = Nothing
End Sub
I'm no expert, but I don't think you need the DELETE part. SELECT INTO is the syntax for making a table. If the table already exists, it's overwritten.
If I need to wait for something, I tend to use DoEvents to allow windows to process any other actions that have been put on hold.
From the help: "Yields execution so that the operating system can process other events."
Found this:
.BeginTrans then
.CommitTrans dbForceOSFlush
as a way to force updates to be written before continuing

Select statement includes a reserved word or an argument name that is misspelled or missing or punctuation is incorrect

I cannot for the life of me figure out why I am getting this error. I am pretty familiar with VB and SQL but am not used to using Access. I have ran my query separately just in access and it works just fine... Below is my code. Any suggestions!?!? Thanks so much!!!
Private Sub Command18_Click()
Dim db As Database
Dim rs As Recordset
Dim sSQL As String
sSQL = "SELECT Count(*) AS Duration" _
& "FROM [Project_Duration_Info] " _
& "WHERE [Project - Consulting Partner] In (Select [CP_Name] from [CP's] " _
& "Where [CP_DDL] = [Forms]![Consulting Partners]![CPs]) " _
& "AND [Project - Actual Complete Date] >= [Forms]![Consulting Partners]![FromDate] " _
& "AND [Project - Actual Complete Date] < [Forms]![Consulting Partners]![ToDate]"
Set db = CurrentDb
Set rs = db.OpenRecordset(sSQL)
If rs.RecordCount > 0 Then
Me.Duration = rs!Durations
Else
Me.Duration = ""
End If
Set rs = Nothing
Set db = Nothing
End Sub
It looks like you are combining VBA and SQL into one statement: [Forms]![Consulting Partners]![CPs] appears to be a variable pulled from the form but embedded within the SQL try
WHERE [CP_DDL] = '" & [Forms]![Consulting Partners]![CPs] & "'
The same logic will need to be applied to the [Forms]![Consulting Partners]![ToDate] and [Forms]![Consulting Partners]![FromDate] and if these are dates you'll probably need to surround them with # (so end result would be #01/01/2012#)