I have a search button which searches in 4 tables. So I made the Sql query with three inner, and I have CheckBoxes so if the CheckBox is checked it adds the conditions to the query. But I have a problem which is:
System.Data.OleDb.OleDbException
Syntax error in the JOIN operation
cmd = New OleDbCommand(Sql, myConnection)
Dim da As OleDbDataAdapter
Dim sql = "SELECT * from (tblDopages AS A INNER JOIN tblMatrice AS B on A.strMatrice = B.strMatrice) INNER JOIN (tblRefMatrice AS C on B.strMatrice = C.strMatrice) INNER JOIN (tblRefMatDetails AS D on C.intIDref = D.intIDRef) WHERE "
If CKBrefech.Checked = True Then
sql = sql & "strRefEch = '" & TBrefech.Text & "' AND "
End If
If CKBmethode.Checked = True Then
sql = sql & "strMethode = '" & CBmethode.Text & "' AND "
End If
If CKBpurif.Checked Then
sql = sql & "strPurif = '" & CBpurif.Text & "' AND "
End If
If CKBmatrice.Checked Then
sql = sql & "strMatrice = '" & CBmatrice.Text & "' AND "
End If
If CKBmol.Checked Then
sql = sql & "strMolecule = '" & CBmol.Text & "' AND "
End If
If CKBechprep.Checked Then
sql = sql & "datDatePrepa >= #DatPrepa AND "
cmd.Parameters.Add("#DatPrepa", OleDbType.Date).Value = DTPechprep.Value.Date
End If
If CKBechau.Checked Then
sql = sql & "datDatePrepa <= #Datau AND "
cmd.Parameters.Add("#Datau", OleDbType.Date).Value = DTPechau.Value.Date
End If
If CKBtrigprepa.Checked = True Then
sql = sql & "strTrigPrepa = '" & TBtrigprepa.Text & "' AND "
End If
If CKBtriganaly.Checked = True Then
sql = sql & "strTrigAnaly = '" & TBtrigAnaly.Text & "' AND "
End If
If CKBappar.Checked = True Then
sql = sql & "strNomTech = '" & CBappar.Text & "' AND "
End If
If CKBnumappar.Checked = True Then
sql = sql & "[strEquip(Appareil)] = '" & CBnumappar.Text & "' AND "
End If
If CKBteneurmini.Checked = True Then
sql = sql & "dblDopage >= " & TBteneurmini.Text & " AND "
End If
If CKBteneurmax.Checked = True Then
sql = sql & "dblDopage <= " & TBteneurmax.Text & " AND "
End If
If GroupBox1.Enabled Then
Try
If CKBnomref.Checked Then
sql = sql & "D.strReferentiel = '" & CBnomref.Text & "' AND "
End If
If CKBniv1.Checked Then
sql = sql & "D.strNIveau1 = '" & CBniv1.Text & "' AND "
End If
If CKBniv2.Checked Then
sql = sql & "D.strNiveau2 = '" & CBniv2.Text & "' AND "
End If
If CKBniv3.Checked Then
sql = sql & "D.strNiveau3 = '" & CBniv3.Text & "' AND "
End If
If CKBniv4.Checked Then
sql = sql & "D.strNiveau4 = '" & CBniv4.Text & "' AND "
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End If
If sql.EndsWith(" AND ") Then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If sql.EndsWith(" WHERE ") Then
sql = sql.Substring(0, sql.Length - 7)
End If
' cmd = New OleDbCommand(sql, myConnection)
cmd.CommandText = sql
cmd.Connection = myConnection
Dim MyDataSet As New DataSet
da = New OleDbDataAdapter(sql, myConnection)
da.SelectCommand = cmd
da.SelectCommand.Parameters.Add(New OleDbParameter("#DatPrepa", DTPechprep.Value)) 'adding date parameters to datatable
da.SelectCommand.Parameters.Add(New OleDbParameter("#datau", DTPechprep.Value)) 'adding date parameters to datatable
'da.SelectCommand.Parameters.Add(New OleDbParameter("#Matrice", matrice.ToString)) 'adding Matrice parameters to datatable
da.Fill(MyDataSet, "Matrice")
DataGridView1.DataSource = MyDataSet.Tables("Matrice")
'to focus on first row of DGV after populating it
DataGridView1.Rows(0).Selected = True
LBnumresult.Text = DataGridView1.RowCount - 1
Well you have some syntax errors. Change this:
SELECT *
FROM (tblDopages AS A
INNER JOIN tblMatrice AS B ON A.strMatrice = B.strMatrice)
INNER JOIN (tblRefMatrice AS C ON B.strMatrice = C.strMatrice)
INNER JOIN (tblRefMatDetails AS D ON C.intIDref = D.intIDRef)
WHERE strMethode = 'MarMeth1' AND strPurif = 'MarPurif2'
to this:
SELECT *
FROM ((tblDopages AS A
INNER JOIN tblMatrice AS B ON A.strMatrice = B.strMatrice)
INNER JOIN tblRefMatrice AS C ON B.strMatrice = C.strMatrice)
INNER JOIN tblRefMatDetails AS D ON C.intIDref = D.intIDRef
WHERE strMethode = 'MarMeth1' AND strPurif = 'MarPurif2'
General:
SELECT ...
FROM ((--here N-2 parentesis
table1
JOIN table2 ON ...)
JOIN table3 ON ...)
JOIN table4 ON ...)
JOIN tableN ON ...--here no parentesis
This is the answer I used which contains 2 inner join between 3 tables and left join.
I made first the inner join and finally the left join
Dim sql = "SELECT distinct A.* FROM ((tblMatrice AS B INNER JOIN tblRefMatrice AS C ON B.strMatrice = C.strMatrice) INNER JOIN tblRefMatDetails AS D ON C.intIDref = D.intIDRef) LEFT OUTER JOIN tblDopages AS A on A.strMatrice = B.strMatrice where "
Related
I have an Access database that I am trying to insert, update and delete with SQL commands using VBA from an Excel workbook. My update and insert commands work fine but my delete command freezes Excel. I have tried various methods with and without table aliasing.
Set dbConnection = CreateObject("ADODB.Connection") 'New ADODB.Connection
dbConnection.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data source=C:\Users\me\Desktop\Opstats Import\TG_DB.accdb;"
Set dbCommand = CreateObject("ADODB.Command") 'New ADODB.Command
L = "[Excel 12.0 Xml;HDR=YES;IMEX=2;ACCDB=YES;DATABASE=" & ThisWorkbook.FullName & "].[LImport$]"
With dbCommand
.ActiveConnection = dbConnection
'Update Labour
SQL = "UPDATE tblLabour A" & _
" INNER JOIN " & L & " X" & _
" ON A.PositionID = X.PositionID AND A.Date = X.Date AND A.PayCode = X.PayCode" & _
" SET A.Hours = X.Hours, A.Dollars = X.Dollars"
.CommandText = SQL
.Execute
SQL = "DELETE FROM tblLabour" & _
" WHERE NOT EXISTS (SELECT * FROM " & L & " X WHERE X.PositionID = tblLabour.PositionID AND X.Date = tblLabour.Date AND X.PayCode = tblLabour.PayCode)"
.CommandText = SQL
.Execute
'Insert Labour
SQL = "INSERT INTO tblLabour" & _
" SELECT * FROM " & L & " X" & _
" WHERE NOT EXISTS (SELECT PositionID, Date, PayCode FROM tblLabour A WHERE A.PositionID = X.PositionID AND A.Date = X.Date AND A.PayCode = X.PayCode)"
.CommandText = SQL
.Execute
End With
dbConnection.Close
Set dbCommand = Nothing
Set dbConnection = Nothing
I have also tried:
SQL = "DELETE A FROM tblLabour A" & _
" WHERE NOT EXISTS (SELECT * FROM " & L & " X WHERE X.PositionID = A.PositionID AND X.Date = A.Date AND X.PayCode = A.PayCode)"
.CommandText = SQL
.Execute
Because of my data source, I do not have a primary key and rely on three fields to create a composite primary key so the only way to find records is to match all three fields.
I tested the SQL in an Access query and it seems to work fine.
Try concatenating fields to use as a unique identifier with NOT IN().
SQL = "DELETE FROM tblLabour" & _
" WHERE NOT PositionID & PayCode & [Date] IN (SELECT PositionID & PayCode & [Date] FROM " & L & " X)"
I want to create a pivot table in the active report to display dbf multiple
files records.
I'm trying to use the following code to create the PIVOT but it's not working, resulting in the error I've shown below.
This is the code:
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Private Sub openDB()
Set rs = New ADODB.Recordset
Set cn = New ADODB.Connection
cn.Open "Provider=VFPOLEDB.1;" & _
"Data Source=D:\Monthly\Colony;" & _
"Collating Sequence=MACHINE"
End Sub
Call openDB
rs.Open "SELECT HEDNAME,DEPCODE,DEPNAME," & _
"ISNULL(A,0) as A, ISNULL(B,0) as B, ISNULL(C,0) as C, ISNULL(G,0) as G " & _
"from(SELECT HED.HEDCODE,HED.HEDNAME,payfil01.DEPCODE,payfil01.DEPNAME,payfil12.PARSSCB," & _
"payfil12.EMPSHFT FROM payfil01 INNER JOIN payfil12 ON payfil01.DEPCODE = payfil12.DEPCODE " & _
"INNER JOIN payfil04 ON payfil01.DEPCODE = payfil04.DEPCODE AND payfil12.EMPTYPE = payfil04.EMPTYPE" & _
" AND payfil12.EMPCODE = payfil04.EMPCODE INNER JOIN payfil05 ON payfil12.DEPCODE = payfil05.DEPCODE" & _
" AND payfil12.EMPTYPE = payfil05.EMPTYPE AND payfil12.EMPCODE = payfil05.EMPCODE Inner Join" & _
"(Select DEPCODE HEDCODE,DEPNAME HEDNAME from payfil01 Where RIGHT(DEPCODE,2) = '00')" & _
" HED On HED.HEDCODE = Left(payfil01.DEPCODE,2) + '-00' where ltrim(rtrim(payfil04.empcode))<>''" & _
" and payfil12.parsscb>0)Final PIVOT ( SUM(PARSSCB) FOR EMPSHFT IN ([A],[B],[C],[G]) )pvt order by HEDCODE asc " & _
", cn, adOpenStatic, adLockReadOnly"
Set SS_Summary.DataControl1.Recordset = rs
SS_Summary.DataControl1.Recordset = rs
SS_Summary.Field35.Text = txtReportPeriod.Text
SS_Summary.Show
SS_Summary.Refresh
End Sub
Moreover it tried to use following query:
SELECT hedname,
depcode,
depname,
Sum(CASE
WHEN [empshft] = 'A' THEN parsscb
ELSE 0
END) AS A,
Sum(CASE
WHEN [empshft] = 'B' THEN parsscb
ELSE 0
END) AS B,
Sum(CASE
WHEN [empshft] = 'C' THEN parsscb
ELSE 0
END) AS C,
Sum(CASE
WHEN [empshft] = 'G' THEN parsscb
ELSE 0
END) AS G
FROM (SELECT HED.hedcode,
HED.hedname,
payfil01.depcode,
payfil01.depname,
payfil12.parsscb,
payfil12.empshft
FROM payfil01
INNER JOIN payfil12
ON payfil01.depcode = payfil12.depcode
INNER JOIN payfil04
ON payfil01.depcode = payfil04.depcode
AND payfil12.emptype = payfil04.emptype
AND payfil12.empcode = payfil04.empcode
INNER JOIN payfil05
ON payfil12.depcode = payfil05.depcode
AND payfil12.emptype = payfil05.emptype
AND payfil12.empcode = payfil05.empcode
INNER JOIN (SELECT depcode HEDCODE,
depname HEDNAME
FROM payfil01
WHERE RIGHT(depcode, 2) = '00') HED
ON HED.hedcode = LEFT(payfil01.depcode, 2) + '-00'
WHERE Ltrim(Rtrim(payfil04.empcode)) <> ''
AND payfil12.parsscb > 0) AS final
GROUP BY hedname,
depcode,
depname
ORDER BY depcode ASC
Screenshot of the error:
It looks like you included some of the Recordset.Open parameters into the SQL string:
rs.Open "SELECT HEDNAME,DEPCODE,DEPNAME," & _
"ISNULL(A,0) as A, ISNULL(B,0) as B, ISNULL(C,0) as C, ISNULL(G,0) as G " & _
"from(SELECT HED.HEDCODE,HED.HEDNAME,payfil01.DEPCODE,payfil01.DEPNAME,payfil12.PARSSCB," & _
"payfil12.EMPSHFT FROM payfil01 INNER JOIN payfil12 ON payfil01.DEPCODE = payfil12.DEPCODE " & _
"INNER JOIN payfil04 ON payfil01.DEPCODE = payfil04.DEPCODE AND payfil12.EMPTYPE = payfil04.EMPTYPE" & _
" AND payfil12.EMPCODE = payfil04.EMPCODE INNER JOIN payfil05 ON payfil12.DEPCODE = payfil05.DEPCODE" & _
" AND payfil12.EMPTYPE = payfil05.EMPTYPE AND payfil12.EMPCODE = payfil05.EMPCODE Inner Join" & _
"(Select DEPCODE HEDCODE,DEPNAME HEDNAME from payfil01 Where RIGHT(DEPCODE,2) = '00')" & _
" HED On HED.HEDCODE = Left(payfil01.DEPCODE,2) + '-00' where ltrim(rtrim(payfil04.empcode))<>''" & _
" and payfil12.parsscb>0)Final PIVOT ( SUM(PARSSCB) FOR EMPSHFT IN ([A],[B],[C],[G]) )pvt order by HEDCODE asc " & _
", cn, adOpenStatic, adLockReadOnly" '<--- THIS PART SHOULD NOT BE IN THE STRING!!!
Note that last line with args for the Open method are accidentally in the string. It should be more like this:
rs.Open "SELECT HEDNAME,DEPCODE,DEPNAME," & _
"ISNULL(A,0) as A, ISNULL(B,0) as B, ISNULL(C,0) as C, ISNULL(G,0) as G " & _
"from(SELECT HED.HEDCODE,HED.HEDNAME,payfil01.DEPCODE,payfil01.DEPNAME,payfil12.PARSSCB," & _
"payfil12.EMPSHFT FROM payfil01 INNER JOIN payfil12 ON payfil01.DEPCODE = payfil12.DEPCODE " & _
"INNER JOIN payfil04 ON payfil01.DEPCODE = payfil04.DEPCODE AND payfil12.EMPTYPE = payfil04.EMPTYPE" & _
" AND payfil12.EMPCODE = payfil04.EMPCODE INNER JOIN payfil05 ON payfil12.DEPCODE = payfil05.DEPCODE" & _
" AND payfil12.EMPTYPE = payfil05.EMPTYPE AND payfil12.EMPCODE = payfil05.EMPCODE Inner Join" & _
"(Select DEPCODE HEDCODE,DEPNAME HEDNAME from payfil01 Where RIGHT(DEPCODE,2) = '00')" & _
" HED On HED.HEDCODE = Left(payfil01.DEPCODE,2) + '-00' where ltrim(rtrim(payfil04.empcode))<>''" & _
" and payfil12.parsscb>0)Final PIVOT ( SUM(PARSSCB) FOR EMPSHFT IN ([A],[B],[C],[G]) )pvt order by HEDCODE asc " & _
, cn, adOpenStatic, adLockReadOnly
I have a search button which looks up for data only in tblDopage but there is a field strMatrice in this table that is linked to table tblMatrice. So if the user is searching for Matrice I should retrieve Matrice from tblMatrice and innerjoin it with tblDopage on strMatrice, it's like a search inside search and the result of searching for matrice is more than 1 result so that I have many results which i should link them with tblDopage to display the final result. What shall i do, I spended 3 days searching for a solution.
I retrieved strMatrice from tblMatrice and populated a dataset with the result but I don't know how to innerjoin between a dataset and table in the database which is the tblDopage
Help is very appreciated, Thank you in advance
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim sql = "SELECT * from tblDopages WHERE "
cmd = New OleDbCommand(Sql, myConnection)
Dim da As OleDbDataAdapter
If CKBrefech.Checked = True Then
sql = sql & "strRefEch = '" & TBrefech.Text & "' AND "
End If
If CKBmethode.Checked = True Then
sql = sql & "strMethode = '" & CBmethode.Text & "' AND "
End If
If CKBpurif.Checked Then
sql = sql & "strPurif = '" & CBpurif.Text & "' AND "
End If
If CKBmatrice.Checked Then
sql = sql & "strMatrice = '" & CBmatrice.Text & "' AND "
End If
If CKBmol.Checked Then
sql = sql & "strMolecule = '" & CBmol.Text & "' AND "
End If
If CKBechprep.Checked Then
sql = sql & "datDatePrepa >= #DatPrepa AND "
cmd.Parameters.Add("#DatPrepa", OleDbType.Date).Value = DTPechprep.Value.Date
End If
If CKBechau.Checked Then
sql = sql & "datDatePrepa <= #Datau AND "
cmd.Parameters.Add("#Datau", OleDbType.Date).Value = DTPechau.Value.Date
End If
If CKBtrigprepa.Checked = True Then
sql = sql & "strTrigPrepa = '" & TBtrigprepa.Text & "' AND "
End If
If CKBtriganaly.Checked = True Then
sql = sql & "strTrigAnaly = '" & TBtrigAnaly.Text & "' AND "
End If
If CKBappar.Checked = True Then
sql = sql & "strNomTech = '" & CBappar.Text & "' AND "
End If
If CKBnumappar.Checked = True Then
sql = sql & "[strEquip(Appareil)] = '" & CBnumappar.Text & "' AND "
End If
If CKBteneurmini.Checked = True Then
sql = sql & "dblDopage >= " & TBteneurmini.Text & " AND "
End If
If CKBteneurmax.Checked = True Then
sql = sql & "dblDopage <= " & TBteneurmax.Text & " AND "
End If
'if referentiel is enabled
myConnection.Close()
If CKBnomref.Checked Then
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\Users\Marwan_Albanna\Desktop\Autocontrol.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
'Get IDref from table tblRefMatDetails and then make an innerjoin with tblRefMatrice to retrieve the matrice and insert it into the search query of tblDopages
Dim query = "select distinct a.strMatrice from tblRefMatrice a INNER JOIN tblRefMatDetails b on a.intIDref=b.intIDRef where "
cmd = New OleDbCommand(query, myConnection)
Try
If CKBnomref.Checked Then
query = query & "b.strReferentiel = '" & CBnomref.Text & "' AND "
End If
If CKBniv1.Checked Then
query = query & "b.strNIveau1 = '" & CBniv1.Text & "' AND "
End If
If CKBniv2.Checked Then
query = query & "b.strNiveau2 = '" & CBniv2.Text & "' AND "
End If
If CKBniv3.Checked Then
query = query & "b.strNiveau3 = '" & CBniv3.Text & "' AND "
End If
If CKBniv4.Checked Then
query = query & "b.strNiveau4 = '" & CBniv4.Text & "' AND "
End If
' Remove the last AND if any ....'
If query.EndsWith(" AND ") Then
query = query.Substring(0, query.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If query.EndsWith(" WHERE ") Then
query = query.Substring(0, query.Length - 7)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
cmd.CommandText = query
cmd.Connection = myConnection
Dim MyDataTable As New DataTable
Dim da As New OleDbDataAdapter(query, myConnection)
da.Fill(MyDataTable)
Dim row As DataRow
For Each row In MyDataTable.Rows
Dim strMatrice As String
strMatrice = row("strMatrice")
Next row
DataGridView2.DataSource = MyDataTable
'to focus on first row of DGV after populating it
DataGridView2.Rows(0).Selected = True
myConnection.Close()
Dim matrice As String
For x As Integer = 0 To DataGridView2.Rows.Count - 2
matrice = DataGridView2.Rows(x).Cells(0).Value
sql = sql & " strMatrice = '" & matrice.ToString & "' AND "
Dim row As DataRow
For Each row As DataRow In MyDataTable.Rows
matrice = row.Item("Detail")
Next row
Next
End If
' Remove the last AND if any ....'
If sql.EndsWith(" AND ") Then
sql = sql.Substring(0, sql.Length - 4)
End If
' Remove the WHERE if no textbox has been filled....'
If sql.EndsWith(" WHERE ") Then
sql = sql.Substring(0, sql.Length - 7)
End If
' cmd = New OleDbCommand(sql, myConnection)
cmd.CommandText = sql
cmd.Connection = myConnection
Dim MyDataSet As New DataSet
da = New OleDbDataAdapter(sql, myConnection)
da.SelectCommand = cmd
da.SelectCommand.Parameters.Add(New OleDbParameter("#DatPrepa", DTPechprep.Value)) 'adding date parameters to datatable
da.SelectCommand.Parameters.Add(New OleDbParameter("#datau", DTPechprep.Value)) 'adding date parameters to datatable
'da.SelectCommand.Parameters.Add(New OleDbParameter("#Matrice", matrice.ToString)) 'adding Matrice parameters to datatable
da.Fill(MyDataSet, "Matrice")
DataGridView1.DataSource = MyDataSet.Tables("Matrice")
'to focus on first row of DGV after populating it
DataGridView1.Rows(0).Selected = True
LBnumresult.Text = DataGridView1.RowCount - 1
I have a vehicle database and would like to show "related" vehicles when a user clicks to view a vehicle. For instance, the user views a '2013 Chevy Tahoe' that is listed by dealership 'ABC Dealers'.
I need to create a SQL statement to grab 4 vehicles that are similar to the vehicle they are viewing. Here is the order of importance for now:
1) Dealer Listings (d_id)(Show vehicles also listed by that dealer)
2) Vehicle Category (vc_id)(Vehicle category such as Car, Truck, SUV, etc.)
3) Vehicle Make (vm_id)(Vehicle make such as Ford, Chevy, Lexus, etc.)
I have created a SQL statement, but it does not seem to do what I am looking for it to do. Can anyone offer any suggestions on how to properly build a SQL statement to grab the most relevant records in the order defined above?
strSQL = "SELECT TOP 4 v.v_id, vm.vm_name, v.v_year, v.v_model, v.v_search_price, d.d_name, u.u_name " & _
"FROM tbl_Vehicles v " & _
"LEFT JOIN tbl_VehicleMake vm ON vm.vm_id = v.vm_id " & _
"LEFT JOIN tbl_Dealers d ON d.d_id = v.d_id " & _
"LEFT JOIN tbl_Users u ON u.u_id = v.u_id " & _
"WHERE v.v_processed = 1 AND v.v_active = 1 AND v.v_id <> " & v_id
If Not CheckBlank(d_id) Then
strSQL = strSQL & " OR v.d_id = " & d_id
End If
If Not CheckBlank(vm_id) Then
strSQL = strSQL & " OR v.vm_id = " & vm_id
End If
If Not CheckBlank(vc_id) Then
strSQL = strSQL & " OR v.vc_id = " & vc_id
End If
strSQL = strSQL & " ORDER BY v.d_id, v.vc_id, v.vm_id"
I have a couple of thoughts for you.
Your current query has some ANDs and some ORs. You may need brackets to indicate your preferred order of operations, for example:
strSQL = "SELECT TOP 4 v.v_id, vm.vm_name, v.v_year, v.v_model, v.v_search_price, d.d_name, u.u_name " & _
"FROM tbl_Vehicles v " & _
"LEFT JOIN tbl_VehicleMake vm ON vm.vm_id = v.vm_id " & _
"LEFT JOIN tbl_Dealers d ON d.d_id = v.d_id " & _
"LEFT JOIN tbl_Users u ON u.u_id = v.u_id " & _
"WHERE v.v_processed = 1 AND v.v_active = 1 AND v.v_id <> " & v_id
If Not CheckBlank(d_id) Or Not CheckBlank(vm_id) Or Not CheckBlank(vc_id) Then
strSQL = strSQL & "("
End If
If Not CheckBlank(d_id) Then
strSQL = strSQL & " OR v.d_id = " & d_id
End If
If Not CheckBlank(vm_id) Then
strSQL = strSQL & " OR v.vm_id = " & vm_id
End If
If Not CheckBlank(vc_id) Then
strSQL = strSQL & " OR v.vc_id = " & vc_id
End If
If Not CheckBlank(d_id) Or Not CheckBlank(vm_id) Or Not CheckBlank(vc_id) Then
strSQL = strSQL & ")"
End If
strSQL = strSQL & " ORDER BY v.d_id, v.vc_id, v.vm_id"
But based on what you wrote in your question, you may be better with a query that uses the ORDER BY clause to get the most appropriate records based on the criteria you specified.
strSQL = "SELECT TOP 4 v.v_id, vm.vm_name, v.v_year, v.v_model, v.v_search_price, d.d_name, u.u_name " & _
"FROM tbl_Vehicles v " & _
"LEFT JOIN tbl_VehicleMake vm ON vm.vm_id = v.vm_id " & _
"LEFT JOIN tbl_Dealers d ON d.d_id = v.d_id " & _
"LEFT JOIN tbl_Users u ON u.u_id = v.u_id " & _
"WHERE v.v_processed = 1 AND v.v_active = 1 AND v.v_id <> " & v_id & " ORDER BY"
If Not CheckBlank(d_id) Or Not CheckBlank(vm_id) Or Not CheckBlank(vc_id) Then
If Not CheckBlank(d_id) Then
strSQL = strSQL & " CASE WHEN v.d_id = " & d_id & " THEN 0 ELSE 1 END,"
End If
If Not CheckBlank(vm_id) Then
strSQL = strSQL & " CASE WHEN v.vm_id = " & vm_id & " THEN 0 ELSE 1 END,"
End If
If Not CheckBlank(vc_id) Then
strSQL = strSQL & " CASE WHEN v.vc_id = " & vc_id & " THEN 0 ELSE 1 END,"
End If
strSQL = Left(strSQL, Len(strSQL) - 1)
Else
strSQL = strSQL & "v.d_id, v.vc_id, v.vm_id"
End If
This query will still give you results even if there are no vehicles for that dealer, make or category, so you will always have related vehicles (assuming you have at least 5 records).
It looks like the OR clauses you're using are not going to bring you you want. Assuming I'm understanding the snippet and the unseen db correctly, you need to create a subclause of the OR statements that is "ANDED" in. Try the following, after the initial strSQL assignment:
...
dim strSubClause
strSubClause = ""
If Not CheckBlank(d_id)) Then
strSubClause = "v.d_id = " & d_id
End If
If Not CheckBlank(vm_id) Then
If len(strSubClause) > 0 then
strSubClause = strSubClause & " OR v.vm_id = " & vm_id
Else
strSubClause = "v.vm_id = " & vm_id
End If
End If
If Not CheckBlank(vc_id) Then
If len(strSubClause) > 0 then
strSubClause = strSubClause & " OR v.vc_id = " & vc_id
Else
strSubClause = "v.vc_id = " & vc_id
End if
End If
If len(strSubClause) > 0 then
strSQL = " AND (" & strSubClause & ")"
End If
strSQL = strSQL & " ORDER BY v.d_id, v.vc_id, v.vm_id"
So, assuming all of your checks came back with values, you'd have a where clause that looks like:
...WHERE v.v_processed = 1 AND v.v_active = 1 AND v.v_id <> NNN AND (v.d_id = XXX OR v.vm_id = YYY OR v.vc_id = ZZZ) ORDER BY v.d_id, v.vc_id, v.vm_id
Does that make sense and/or get you closer or all the way to where you're wanting to go?
I have a ComboBox named ComboBox_Calculations in my program that is filled with calculations (ex. Current_Ratio, Total_Debt_To_Assets_Ratio). ComboBox_Calculations is actually populated by using the contents of a field in a tabled called Criteria in my Access Database.
I need to create a saved query called Calculations_Quarterly. The query needs to have fields of Ticker, [Year], Period and then one field for every item in ComboBox_Calculations. So for this example I would also need fields named Current_Ratio and Total_Debt_To_Assets_Ratio.
Here is what my tables look like so far:
Criteria
Calculations_Quarterly
Here is the code I have that adds one field at a time (in this case Current_Ratio. But I do not know how add a column for every item in ComboBox_Calculations
con.Open()
Dim dr As OleDbDataReader
Dim cmd6 As New OleDb.OleDbCommand("SELECT Calculation, [Interval], Formula FROM Criteria", con)
dr = cmd6.ExecuteReader
dr.Read()
Dim Calculation = dr("Calculation").ToString
Dim Interval = dr("Interval").ToString
Dim Formula = dr("Formula").ToString
Dim Where_Statement As String
If Interval = "Daily" Then
Where_Statement = "WHERE Historical_Stock_Prices.[Date] < " & DateTime.Now.Date & ""
ElseIf Interval = "MRQ" Then
Where_Statement = "WHERE Income_Statements.Period < 5"
ElseIf Interval = "TTM" Then
Where_Statement = "WHERE Income_Statements.Period < 5"
ElseIf Interval = "5 Year" Then
Where_Statement = "WHERE Income_Statements.Period = 5"
Else
Where_Statement = ""
End If
Try
Dim cmd2 As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
cmd2.ExecuteNonQuery()
Catch ex As Exception
Finally
Dim cmd2a As OleDbCommand = New OleDbCommand("DROP PROCEDURE " & Calculation & "", con)
cmd2a.ExecuteNonQuery()
Dim cmd2b As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)
cmd2b.ExecuteNonQuery()
End Try
con.Close
I couldnt find the name of you combobox or how it is filled so assuming it is named Combo1, and you filled it using Combo1.Items.Add("..."), you would want something like this:
Dim sb as new System.Text.StringBuilder("")
For each s as string in Combo1.Items
sb.Append("," & s)
Next
And then in your SQL:
Dim cmd2 As OleDbCommand = New OleDbCommand("CREATE PROC " & Calculation & " AS SELECT Income_Statements.Ticker, Income_Statements.[Year], Income_Statements.Period, " & Formula & " AS " & Calculation & sb.ToString & " FROM Income_Statements INNER JOIN Balance_Sheets ON (Income_Statements.Ticker = Balance_Sheets.Ticker) AND (Income_Statements.[Year] = Balance_Sheets.[Year]) AND (Income_Statements.Period = Balance_Sheets.Period)" & Where_Statement & "", con)