I am having troubles with a VBA SQL JOIN. I Keep Getting A "Join Expression Not Supported" Error. The Following Code Works In The Query Design View but seems to throw an error when in vba.
Dim Rs As DAO.RecordSet
Set Rs = CurrentDb.OpenRecordset( _
"SELECT Schools.ID, Schools.[School Name],Schools.Address, Schools.Postcode, Schools.[Principal name], " & _
"Schools.[E-Mail], Schools.Phone, Schools.Region, Schools.JTHE, Schools.[Social Status], Events.Program " & _
"FROM Schools INNER JOIN Events ON Schools.ID = Events.School WHERE ((Schools.Region = '" & RegionOne & _
"' Or Schools.Region = '" & RegionTwo "' Or Schools.Region = '" & RegionThree "' Or Schools.Region = '" & _
RegionFour "') AND (Schools.JTHE = " & JTHE1 & " Or Schools.JTHE = " & JTHE2 ") AND (Schools.[Social Status] = '" & _
StatusBox.Value "') AND (Events.Program = '" & ProgramBox.Value & "'));")
This Similar Query Works
Set Rs = CurrentDb.OpenRecordset("SELECT * FROM Schools WHERE " & _
"(((Schools.Region)='" & RegionOne & _
"' Or (Schools.Region)='" & RegionTwo & _
"' Or (Schools.Region)='" & RegionThree & _
"' Or (Schools.Region)='" & RegionFour & _
"') AND ((Schools.[Social Status])='" & StatusBox.Value & _
"') AND ((Schools.JTHE)=" & JTHE1 & " Or (Schools.JTHE)=" & JTHE2 & "));")
Any help would be greatly appreciated.
I'm not entirely sure why is that. It is hard to spot error when your doing it on VBA, unlike if your in an actual SQL Management studio where you can spot the lines that errors out. Nonetheless, you may try this:
Set Rs = CurrentDb.OpenRecordset( _
"SELECT Schools.ID, Schools.[School Name], Schools.Address, " & _
"Schools.Postcode, Schools.[Principal name], Schools.[E-Mail], " & _
"Schools.Phone, Schools.Region, Schools.JTHE, Schools.[Social Status], " & _
"Events.Program " & _
"FROM Schools " & _
"INNER JOIN Events " & _
"ON Schools.ID = Events.School " & _
"WHERE Schools.Region IN (" & _
"'" & RegionOne & "'," & _
"'" & RegionTwo & "'," & _
"'" & RegionThree & "'," & _
"'" & RegionFour & "') " & _
"AND Schools.JTHE IN (" & JTHE1 & ", " & JTHE2 & ") " & _
"AND Schools.[Social Status]='" & StatusBox.Value & "' " & _
"AND Events.Program='" & ProgramBox.Value & "';")
I formatted it as such to give you the story of the query (and that is how I will write it in SQL). Not really a direct to the point answer to your question but I just simplified your OR statements and instead uses IN. You might get a:
Too many continuous line error
So adjust the concatenation of strings. I have not tested this of course (although it compiles) but my goal is to give you idea on a possible way to do it. HTH.
Related
Error Error 1 Operator '&' is not defined for types 'String' and 'System.Windows.Forms.TextBox'.
What is wrong with this????!??
SQL = "UPDATE ATG_PP_QTE_HEAD SET " & _
"PART = '" & txtPart.Text & "', " & _
"LOCATION = '" & txtLoc.Text & "', " & _
"DESCRIPTION = '" & txtDescription.Text & "', " & _
"CUSTOMER = '" & txtCustID.Text & "', " & _
"CONTACT_NAME = '" & txtContactName.Text & "', " & _
"CONTACT_PHONE = '" & txtPhone.Text & "', " & _
"CONTACT_EMAIL = '" & txtEmail.Text & "', " & _
"LEAD_TIME = '" & txtLead.Text & "', " & _
"SETUP = " & txtSetup.Text & ", " & _
"WEIGHTPP = " & txtPCWT.Text & ", " & _
"NOTES = '" & txtNotes.Text & "', " & _
"LAST_MODIFIED = '" & DateTime.Now & "', " & _
"LABOR_RATE = " & txtLabor.Text & ", " & _
"OVERHEAD = " & txtOH.Text & ", " & _
"GA = " & txtGA.Text & ", " & _
"SORT_CODE = '" & txtSortCode.Text & "', " & _
"REFERENCE = '" & txtReference.Text & "', " & _
"PL = '" & txtPL.Text & "', " & _
"CUST_DRAW_NO = '" & txtCustDraw.Text & "', " & _
"COMMISSION = " & txtCommission.Text & ", " & _
"PCWT = " & txtPCWT & _
"WHERE QUOTE_ID = " & txtQuoteID.Text
What is wrong with this????!??
Quite a bit, actually. But let's start with the error itself...
On this line:
"PCWT = " & txtPCWT & _
You're trying to concatenate a TextBox to a String. As the error states, you can't do that. Perhaps you meant to use the .Text property:
"PCWT = " & txtPCWT.Text & _
Now, what else is wrong?
First, your code is highly vulnerable to SQL injection attacks. You're going to want to use parameterized queries instead of executing user input as code.
Second, using parameterized queries will make the code a lot easier to read and support, which will make errors like this much easier to find.
Third, on this line there's a significant potential for bugs:
"LAST_MODIFIED = '" & DateTime.Now & "', " & _
Using parameterized queries will remove the culture-dependent string representations from the query and use the actual DateTime data in the query. And you should also get into the habit of using DateTime.UtcNow instead, as having a consistent non-timezone-dependent value is going to make things a lot easier when you have to deal with multiple time zones.
I have an excel userform with various textboxes, some are fields to enter dates. The user can then save their entries.
At this point, I connect to an access backend via an ADO connection. The values entered by a user are passes to an SQL string, e.g.
strSQL = "UPDATE tblDECONVERSION_DATA SET tblDECONVERSION_DATA.Status = '" & NewBusiness_WorkQueue.Decon_CaseStatus & "', " & _
"tblDECONVERSION_DATA.DMS = '" & NewBusiness_WorkQueue.Decon_DMS & "', " & _
"tblDECONVERSION_DATA.DateRecieved = #" & Format(NewBusiness_WorkQueue.Decon_DateRecieved, "mm/dd/yyyy") & "#, " & _
"tblDECONVERSION_DATA.WireDate = #" & Format(NewBusiness_WorkQueue.Decon_WireDate, "mm/dd/yyyy") & "#, " & _
"tblDECONVERSION_DATA.LastEditXID = '" & CurrUser & "', tblDECONVERSION_DATA.LastEditDate = #" & Now & "# " & _
"WHERE (((tblDECONVERSION_DATA.CaseID)=" & ID & "));"
adoRecSet.Open Source:=strSQL, ActiveConnection:=dbconnect, CursorType:=adOpenDynamic, LockType:=adLockOptimistic
However, some of the date fields can be left blank, meaning for example the NewBusiness_WorkQueue.Decon_DateRecieved variable being empty. This causes a syntax error. How can I pass a Null or Empty date variable in the SQL statement that both VBA and the access database will accept?
strSQL = "UPDATE tblDECONVERSION_DATA SET tblDECONVERSION_DATA.Status = '" & _
NewBusiness_WorkQueue.Decon_CaseStatus & "', " & _
"tblDECONVERSION_DATA.DMS = '" & NewBusiness_WorkQueue.Decon_DMS & "', " & _
"tblDECONVERSION_DATA.DateRecieved = " & _
DateOrNull(NewBusiness_WorkQueue.Decon_DateRecieved) & ", " & _
"tblDECONVERSION_DATA.WireDate = " & _
DateOrNull(NewBusiness_WorkQueue.Decon_WireDate) & ", " & _
"tblDECONVERSION_DATA.LastEditXID = '" & CurrUser & _
"', tblDECONVERSION_DATA.LastEditDate = #" & Now & "# " & _
"WHERE tblDECONVERSION_DATA.CaseID=" & ID & ";"
An example function:
Function DateOrNull(v) As String
Dim rv as String
If IsDate(v) Then
rv = " #" & Format(v, "mm/dd/yyyy") & "# "
Else
rv = " null "
End If
DateOrNull = rv
End Function
I need some help with this, sorry, I am new in VBA and I am trying to run a update query which should obtain a value from a variable and update an already existing table. This is done using VBA. On executing no error message is shown but the table isn't updated with the new value. The code is as follows:
Query = "UPDATE Results " & _
"SET fk_Report='" & Report & "'" & _
",fk_Name='" & Namevar & "'" & _
",fk_Age='" & Agevar & "'" & _
",fk_Sex='" & Sexvar & "'" & _
"WHERE [Count]='" & Countvar & "'" & _
",[Positives]='" & Posvar & "'" & _
",[Negatives]='" & Negvar & "'" & _
",[Unknow]='" & Unkvar & "';"
CurrentDb.Execute (Query)
If somebody can help...
You don't need the commas in the where clause
Query = "UPDATE Results " & _
"SET fk_Report='" & Report & "'" & _
",fk_Name='" & Namevar & "'" & _
",fk_Age='" & Agevar & "'" & _
",fk_Sex='" & Sexvar & "'" & _
"WHERE [Count]='" & Countvar & "' " & _
"AND [Positives]='" & Posvar & "' " & _
"AND [Negatives]='" & Negvar & "' " & _
"AND [Unknow]='" & Unkvar & "';"
CurrentDb.Execute (Query)
use AND instead of , (comma) after WHERE clause
I have this code to update database with SQL but it is not working
Call Connect_to_db
strSQL = "UPDATE StockTable " & _
"SET StockTable.Selected = '" & Sheets("InfoStockDes").Range("g" & x) & "' " & _
"WHERE OwnerName = '" & Sheets("InfoStockDes").Range("a" & x) & WHERE OwnerShipMethod = Sheets("InfoStockDes").Range("b" & g) & WHERE StockName = Sheets("InfoStockDes").Range("c" & g) & WHERE Quantity = Sheets("InfoStockDes").Range("d" & g) "' "
cn.Execute strSQL
Call Close_db
This is your code as posted, but then with some extra linebreaks and outlining. Maybe you can spot the obvious errors yourself better now?
Call Connect_to_db
strSQL = "UPDATE StockTable " & _
"SET StockTable.Selected = '" & Sheets("InfoStockDes").Range("g" & x) & "' " & _
"WHERE OwnerName = '" & Sheets("InfoStockDes").Range("a" & x) & _
WHERE OwnerShipMethod = Sheets("InfoStockDes").Range("b" & g) & _
WHERE StockName = Sheets("InfoStockDes").Range("c" & g) & _
WHERE Quantity = Sheets("InfoStockDes").Range("d" & g) "' "
cn.Execute strSQL
Call Close_db
In this version I have changed the extra WHERE clauses to AND, and I haev added some obviously missing " and '.
Call Connect_to_db
strSQL = "UPDATE StockTable " & _
"SET StockTable.Selected = '" & Sheets("InfoStockDes").Range("g" & x) & "' " & _
"WHERE OwnerName = '" & Sheets("InfoStockDes").Range("a" & x) & "' " & _
"AND OwnerShipMethod = '" & Sheets("InfoStockDes").Range("b" & g) & "' " & _
"AND StockName = '" & Sheets("InfoStockDes").Range("c" & g) & "' " & _
"AND Quantity = '" & Sheets("InfoStockDes").Range("d" & g) & "' "
cn.Execute strSQL
Call Close_db
I guess this shoudl work better allready, if it doesn't please tell us what is not working, what error messages, if any, you are getting, and please show the actual content of strSQL before yuo execute it. That string should contain a straightforward SQL statement, but there might be errors in it, so have a look at that and, if necessary, post it for us to look at :)
What I am trying to do is make a line of text appear every 50 strings read. I was trying to find a reaminder function to use on the GlobalVariables.TransferTracker interger, but I couldn't find anything online. Is there such a funciton? Or a differen't/better way to do this? If it helps here is my code:
Do While TransferRecord.Read()
'Start of writing to the SQL server.
SQLServerConnection.Open()
'SQL statement to transfer all the data that fits the requirements to the SQL server.
Dim SQLCommand1 As New SqlCommand("INSERT INTO dbo.b_Pulp_PI_Forte (" & _
"mill, " & _
"keyprinter_datetime, " & _
"bale_line_num, " & _
"pulp_line_id, " & _
"bale_id, " & _
"drop_datetime, " & _
"layboy_position, " & _
"bale_gross_weight, " & _
"gross_value_flag, " & _
"bale_airdry_pct, " & _
"airdry_value_flag, " & _
"sheets_per_bale, " & _
"grader_test_flag, " & _
"dropped_num, " & _
"created_by, " & _
"CreatedDateTime, " & _
"Who_did_it, " & _
"Last_change_datetime) " & _
"VALUES (" & _
"'850', " & _
"'" & ProdDate & "', " & _
"'" & BaleLineNum & "', " & _
"'" & BaleLine & "', " & _
"'" & BaleNumber & "', " & _
"'" & ProdDate & "', " & _
"'0', " & _
"'" & GrossWeight & "', " & _
"'" & GrossWeightFlag & "', " & _
"'" & AirDry & "', " & _
"'" & AirDryFlag & "', " & _
"'0', " & _
"'N', " & _
"'0', " & _
"'BaleTrac', " & _
"'" & Date.Now & "', " & _
"'BaleTrac', " & _
"'" & Date.Now & "')")
'If DisplayCode is checked this will be printed to the screen.
If ApplicationPropertiesWindow.DisplayCodechkbx.Checked = True Then
MainTextBox.AppendText(Environment.NewLine & SQLCommand1.CommandText)
GlobalVariables.DisplayCode = True
End If
'Executing the SQL statement.
SQLCommand1.Connection = SQLServerConnection
SQLCommand1.ExecuteNonQuery()
SQLServerConnection.Close()
GlobalVariables.TransferTracker = GlobalVariables.TransferTracker + 1
'This is where I would like to have the remainder function.
'Making message to show that program is still running.
If GlobalVariables.TransferTracker = 50 Then
MainTextBox.AppendText(Environment.NewLine & "50 records transferred.")
End If
Loop
Right now I just have it set up so it will fire at 50 records, because I couldn't find the function.
The remainder is an operator in VB, Mod:
If GlobalVariables.TransferTracker Mod 50 = 0 Then …
As a general advice, don’t write … = True in your conditions. Its redundancy is redundant.