SQL Syntax Error in Update Statement - Combining multiple fields - sql

Ok for the life of me I can't get this. I just haven't ever combined multiple fields and it's throwing me off as far as syntax goes. I know I'm supposed to single quote the |'s, but do I single quote the string fields? Where am I messing up here?
The error I get is simply "Syntax Error in Update Statement"
CurrentDb.Execute "UPDATE tblFinal SET (tblFinal.[Short Item Description] =
& tblFinal.[2 Digit Year] & '|' & tblFinal.[License Type] & '|'
& trim(tblFinal.[License Number]) & '|' " & _
"tblFinal.[State] & '|' & tblFinal.[City of Store])"

I don't know much about Access, but I think you just have some errant double quotes in the mix:
CurrentDb.Execute "UPDATE tblFinal SET tblFinal.[Short Item Description] = tblFinal.[2 Digit Year] & '|'& tblFinal.[License Type] & '|'& trim(tblFinal.[License Number]) & '|'& tblFinal.[State] & '|'& tblFinal.[City of Store]"
You just need single quotes around the literal text you're concatenating, and all fields can be concatenated with just &.

Watch your line continuation characters and quotes:
Dim sSQL As String
Dim db As Database
Set db = CurrentDb
sSQL = "UPDATE tblFinal SET (tblFinal.[Short Item Description] = " _
& "tblFinal.[2 Digit Year] & '|' & tblFinal.[License Type] & '|' " _
& "trim(tblFinal.[License Number]) & '|' " _
& "tblFinal.[State] & '|' & tblFinal.[City of Store])"
db.Execute sSQL, dbFailonError
It is nearly always best to create the SQL string first, it is much easier to debug. It is also best to use an instance of CurrentDb.

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)

How to delete rows in ms access VBA based on multiple attributes

How do I delete rows in ms access VBA based on multiple attributes?
I have written the code below, but it doesn't seem to work.
CurrentDb.Execute "DELETE * FROM StaffAtMeeting" & _
"WHERE RoomID =& Me.field1 AND MeetingDate = Me.field2 AND MeetingTime = Me.field3;"
Maybe I am missing some " (Double Quotes) and some & (Ampersands) ?
You are missing open/close " (Double Quotes) and some & (Ampersands)
currentdb.execute "DELETE * " & _
"FROM StaffAtMeeting " & _
"WHERE(((RoomID) =" & me.field1 & " AND (MeetingDate) =#" & me.field2 & "# AND (MeetingTime) =#" & me.field3 & "#));"
When you write a string statement in VBA you need an opening and closing double quotes, the ampersand acts as a concatenation. The underscore lets the code know to continue on the next line.
Since your variables are not part of the string, you have to end the string, concatenate the variable, then reopen the string. The # (pound sign/hash tag/Number sign) signifies SQL you are using a date or time.

SQL Variable in Where Clause

Dim varCity As String
varCity = Me.txtDestinationCity
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE" & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"
I am trying to select the states for the selected city. There is a drop down box with a list of cities. That box is titled txtDestinationCity.
It says I have an error in my FROM clause.
Thank you
You miss a space and some quotes. How about:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE '" & Me.txtDestinationCity & "' = [TDestinationType].[tPreTravelDestinationCity]"
Copy that next to your original to see the difference.
And for reasons SQL, PLEASE reverse the comparison. Always mention the column left and the value right:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = '" & Me.txtDestinationCity & "'"
Since the quotes are annoying and easy to miss, i suggest defining a function like this:
Public Function q(ByVal s As String) As String
q = "'" & s & "'"
End Function
and then write the SQL string like that:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(Me.txtDestinationCity)
This makes sure you ALWAYS get both quotes at the right places and not get confused by double-single-double quote sequences.
If you care about SQL-injection (yes, look that up), please use the minimum
Public Function escapeSQL(sql As String) As String
escapeSQL = Replace(sql, "'", "''")
End Function
and use it in all places where you concatenate user-input to SQL-clauses, like this:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
Lastly, breakt it for readability. I doubt your editor shows 200 characters wide:
Me.txtDestinationState.RowSource = _
"SELECT tPreTravelDestinationState " & _
"FROM [TDestinationType] " & _
"WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
Note the trailing spaces in each line! Without them, the concatenation will not work.
It can be easier to troubleshoot your query construction if you set it to a variable (e.g., strSQL) first. Then you can put a breakpoint and see it right before it executes.
You need a space after WHERE. Change WHERE" to WHERE<space>"
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE " & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"

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

Simple SQL query in Access fails with a missing semicolon error

So, I'm learning Access 2007, Visual Basic, and SQL at the same time. Not ideal.
I have this code attached to a button in a standard wizard-generated interface. I'm trying to copy a line from tblA to tblB. Every time the code is executed I get the message, "Run-time error '3137' Missing semicolon (;) at end of SQL statement."
I'm guessing that it's expecting the SQL statement to terminate earlier, before the WHERE? But without the WHERE, how would I attach the add to a particular line ID?
Private Sub buttonAdd_Click()
Dim strSQL As String
strSQL = "INSERT INTO [tblB]" & _
"VALUES (ID, [Name], [Some value], [Some other value])" & _
"SELECT * FROM tblA" & _
"WHERE ID = '" & Me.ID & "' " & _
";"
DoCmd.RunSQL strSQL
End Sub
Syntax is wrong, you need to remove the "VALUES" keyword.
This is assuming that ID, [Name], [Some value] and [Some other value] are column names of tblB (some hesitation on my part with the last two names having "value").
The VALUES() SQL syntax is used to provide immediate values, but since you're getting the values from tblA, the query should look like:
strSQL = "INSERT INTO [tblB] " & _
"(ID, [Name], [Some value], [Some other value]) " & _
"SELECT * FROM tblA " & _
"WHERE ID = '" & Me.ID & "' " & _
";"
Edit: I also added spaces between tokens. Good catch Nick D, thank for noticing this !
You have put the field names in the values clause instead of after the table name, and there is a space missing between tbla and where. Both the value clause followed by select and the missing space could cause the error message by themselves.
strSQL = "INSERT INTO [tblB] (ID, [Name], [Some value], [Some other value])" & _
"SELECT * FROM tblA " & _
"WHERE ID = '" & Me.ID & "'"
The semicolon at the end is not requiered nowadays. You only need it for separating queries if you run more than one query at a time.
Also, if the ID field is numerical, you should not have apostrophes around the value:
strSQL = "INSERT INTO [tblB] (ID, [Name], [Some value], [Some other value])" & _
"SELECT * FROM tblA " & _
"WHERE ID = " & Me.ID
mjv is correct. You must remove the VALUES keyword and also you should put spaces between keywords, ie:
"SELECT * FROM tblA" & _
"WHERE ID = '" & Me.ID & "' " & _
the above will be joined as "...FROM tblAWHERE ID..."