I've created a dropdown with some column names in a table in my db. When a user selects a column name i want to add a where clause to the query to use this filter.
What i'm trying to do is:
Dim objQuery = (From wc In _dbBellen.dealer_telefonies Order By wc.Bedrijfsnaam Select wc)
'if dropdown has value...
objQuery = objQuery.Where(Function(wc) wc.DynamicColumnName < txtFilterValue1.Text)
The wc.DynamicColumnName has to be replaced by for example wc.Price.
--
The code what i'm tried now after some replies is:
Dim objQuery = (From wc In _dbBellen.dealer_telefonies Order By wc.Bedrijfsnaam Select wc)
If ddlFilterColumn1.SelectedValue <> "" And ddlFilterOperator1.SelectedValue <> "" And txtFilterValue1.Text <> "" Then
Select Case ddlFilterOperator1.SelectedValue
Case "..%"
objQuery = objQuery.Where(Function(wc) wc.WHMCSClient_id Like txtFilterValue1.Text & "%")
Case "%.."
objQuery = objQuery.Where(Function(wc) wc.WHMCSClient_id Like "%" & txtFilterValue1.Text)
Case Else '< > = <>
'objQuery = objQuery.Where(Function(wc) wc.WHMCSClient_id < txtFilterValue1.Text)
'objQuery = objQuery.Where(Function(wc) "wc." + ddlFilterColumn1.SelectedValue.ToString + " < " + txtFilterValue1.Text)
objQuery = objQuery.Where(Function(wc) "wc.WHMCSClient_id < 500")
End Select
End If
Response.Write(objQuery.ToString())
But i am getting the following error (original error is in dutch but it said as follow):
The conversion from string wc.WHMCSClient_id < 500 to type Boolean is invalid.
This is quite an old article, but I think it's still viable
Scott Gu posted about the Dynamic LINQ library a while back which essentially allows you to use strings to query collections in a "LINQ"-type format., i.e. something like this:
Dim objQuery = (From wc In _dbBellen.dealer_telefonies Order By wc.Bedrijfsnaam Select wc)
// if dropdown has value...
Dim result = objQuery.Where("MyColumnName < " + txtFilterValue1.Text);
Here's a link to the full article: Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library)
Related
I want to pull some stuff out of a database using a select query. I have the query i need already written in SQL Server management studio and it works. I tried just copy it in but it doesn't work. I have some other queries that do work and i tried to make it formatted like those, but it'll just see it as string since its between "" those things.
Below is the query, it uses the join function that doesn't appear to be recognized by vb.net. the query also uses certain tables from other parts of the database, those also dont seem to get recognized.
the query:
select th.Thickness, count(th.Thickness)
from dbname..trackinghistory th
join dbname..OrderDetailOptions odo on odo.odKey=th.odKey
join dbname..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.[Group]=odo.optiongroup
and mpo.QuestionKey='KGLASS' and OptionType=5
where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and
left(odo.OptionCode,1) = 'H'
group by th.Thickness
I think i just need a push in the right direction, can someone here help me with how to properly format these type of queries?
my VB.Net code:
Sub SetButtonColor()
btnIsClicked = False
Dim iWeek As Integer = tbWeek.Text
Dim iYear As Integer = tbYear.Text
If sql.hasconnection And iWeek <> 0 Then
Dim dtimeStartDate As DateTime = GetWeekStartDate(tbWeek.Text, tbYear.Text) 'get the startdate from the textboxes week and year
Dim dtimeEndDate As DateTime = DateAdd(DateInterval.Day, 7, dtimeStartDate) 'add 7 days to the startdate to set the enddate
sql.runquery("SELECT th.Thickness, count(th.Thickness)" +
"from FVMASTER..trackinghistory th" +
"join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey" +
"join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.[Group]=odo.optiongroup and mpo.QuestionKey='KGLASS' and OptionType=5" +
"where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and left(odo.OptionCode,1) = 'H'" +
"group by th.Thickness")
If sql.sqldataset.Tables(0).Rows.Count > 0 Then
For Each row As DataRow In sql.sqldataset.Tables(0).Rows
Select Case row("Thickness")
Case 3
btn3.BackColor = Color.Red
Case 4
btn4.BackColor = Color.Red
Case 5
btn5.BackColor = Color.Red
Case 6
btn6.BackColor = Color.Red
Case 8
btn8.BackColor = Color.Red
Case 10
btn10.BackColor = Color.Red
Case 12
btn12.BackColor = Color.Red
Case 15
btn15.BackColor = Color.Red
Case 19
btn19.BackColor = Color.Red
Case 24
btn24.BackColor = Color.Red
End Select
Next
End If
end sub
i have for now just pasted in the query, i know that that wont work
The problem are the missing spaces in the SQL string. Just because the concatentated strings are on different lines, this does not add line breaks to the string.
E.g.,
"from FVMASTER..trackinghistory th" +
"join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey"
results in
"from FVMASTER..trackinghistory thjoin FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey"
As you can see, you get a thjoin in there, which should be th join.
Just write it as a single multiline string (which now includes the line breaks)
sql.runquery("SELECT th.Thickness, count(th.Thickness)
from FVMASTER..trackinghistory th
join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey
join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.[Group]=odo.optiongroup and mpo.QuestionKey='KGLASS' and OptionType=5
where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and left(odo.OptionCode,1) = 'H'
group by th.Thickness")
Alternatively, you can keep your original approach and add the missing spaces at the line end
sql.runquery("SELECT th.Thickness, count(th.Thickness) " +
"from FVMASTER..trackinghistory th " +
"join FVMASTER..OrderDetailOptions odo on odo.odKey=th.odKey " +
"join FVMASTER..MasterPartOptions mpo on mpo.Code=odo.OptionCode and mpo.[Group]=odo.optiongroup and mpo.QuestionKey='KGLASS' and OptionType=5 " +
"where th.DateTime>DATEADD(DAY,-4,getdate()) and th.Code='__A__' and th.StationID='HO4' and left(odo.OptionCode,1) = 'H' " +
"group by th.Thickness")
My query is like but it' not working and giving error "SQL command not properly ended" and the string:HDR.TRX_DT = DTL.TRX_DT AND HDR.BU_TYPE = DTL.BU_TYPE AND HDR.BU_CODE = DTL.BU_CODE
AND HDR.TRX_NO = DTL.TRX_NO AND HDR.RGSTR_NO = DTL.RGSTR_NO AND HDR.TRX_TYP_CD in ('COS') is value in column . i want use that value in where clause of select statement .How will do you that .plz suggest
select * from mdbat.migration_ctrl_all where addition_condition='HDR.TRX_DT = DTL.TRX_DT AND HDR.BU_TYPE = DTL.BU_TYPE AND HDR.BU_CODE = DTL.BU_CODE
AND HDR.TRX_NO = DTL.TRX_NO AND HDR.RGSTR_NO = DTL.RGSTR_NO AND HDR.TRX_TYP_CD in ('COS')';
Escape the ' delimiting the COS string, as said by Alex Larionow. But escape each one with another '
select * from mdbat.migration_ctrl_all where addition_condition='HDR.TRX_DT = DTL.TRX_DT AND HDR.BU_TYPE = DTL.BU_TYPE AND HDR.BU_CODE = DTL.BU_CODE
AND HDR.TRX_NO = DTL.TRX_NO AND HDR.RGSTR_NO = DTL.RGSTR_NO AND HDR.TRX_TYP_CD in (''COS'')';
I have this SQL statement and it joining 2 tables...
SELECT TRIDENT.Maintenance.RCFAs.*, TRIDENT.Maintenance.Equipment.EquipmentName
FROM TRIDENT.Maintenance.RCFAs
LEFT JOIN TRIDENT.Maintenance.Equipment
ON TRIDENT.Maintenance.Equipment.EquipmentId = TRIDENT.Maintenance.RCFAs.EquipmentId
WHERE 1 = 1
Now I have to reference a third table because I have a dropdown by the name of components that we will use to lookup stuff on the table named TRIDENT.Maintenance.RCFAXrefComponents. So if "bolts" is selected from the dropdown it will look up the YEAR and RCFAID which makes a unqiue key for both RCFAXrefComponents and RCFAs and checks if there are any rows in RCFAs that had "bolts" in the component column when looking up that YEAR and RCFAId. A coworker suggested I use an IN clause to check if the YEAR and RCFAId is in that RCFAXrefComponents. He said it might be tricky, but I'm a little lost on how to do this.
Below is the RCFAs table that I want to grab the YEAR and RCFAId values together and lookup on the other to see if that bolt is also there. Then it should bring up the line item on RCFAs table to output to user
this is RCFAXrefComponents table below
Public Shared Function GetRCFAList(rcfaNumber As Integer?, description As String,
failureType As String, equipmentDescription As String, componentSelection As String) As List(Of RCFA)
Dim sql = "SELECT r.*, e.EquipmentName FROM TRIDENT.Maintenance.RCFAs AS r LEFT JOIN TRIDENT.Maintenance.Equipment AS e ON e.EquipmentId = r.EquipmentId JOIN TRIDENT. Maintenance.RCFAXrefComponents AS c ON c.Year = r.Year AND c.RCFAId = r.RCFAId WHERE"
If failureType <> "" Then
sql += " AND RCFAs.FailureType = '" & failureType.ToUpper & "'"
End If
If description <> "" Then
sql += " AND RCFAs.ShortDesc LIKE '%" & description.ToUpper & "%'"
End If
If equipmentDescription <> "" Then
sql += " AND Equipment.EquipmentName LIKE '%" & equipmentDescription.ToUpper & "%'"
End If
If componentSelection <> "" Then
sql += " c.ComponentId = '%" & componentSelection.ToUpper & "%'"
End If
Dim dbConn As New Trident.Core.DBConnection
Dim ds = dbConn.FillDataSet(sql)
Dim tmpList As New List(Of RCFA)
For Each dr As DataRow In ds.Tables(0).Rows
tmpList.Add(New RCFA(New Trident.Objects.Maintenance.RCFA.RCFA(dr)))
Next
Return tmpList
End Function
Just use a simple JOIN with the RFCAXrefComponents table, and a WHERE clause that filters the component ID.
SELECT r.*, e.EquipmentName
FROM TRIDENT.Maintenance.RCFAs AS r
LEFT JOIN TRIDENT.Maintenance.Equipment AS e
ON e.EquipmentId = r.EquipmentId
JOIN TRIDENT.Maintenance.RCFAXrefComponents AS c
ON c.Year = r.Year
AND c.RCFAId = r.RCFAId
WHERE c.ComponentID = 'BOLTS'
I may be confused but it sounds like you need to use EXISTS.
SELECT r.*,
e.EquipmentName
FROM TRIDENT.Maintenance.RCFAs r
LEFT JOIN TRIDENT.Maintenance.Equipment e ON e.EquipmentId = r.EquipmentId
WHERE EXISTS ( SELECT 1
FROM TRIDENT.Maintenance.RCFAXrefComponents c
WHERE c.Year = r.Year
AND c.RCFAId = r.RCFAId
AND c.ComponentId LIKE '%BOLTS%' )
you may not need the c.ComponentId LIKE '%BOLTS%' you might just want c.ComponentId = 'BOLTS'
I have a simple (well easy, not simple) query of "not in" on related tables.
SELECT CompetencyID, CompetencyName FROM Competency
WHERE (Deleted = 0) AND (CompanyID = 1) AND (CompetencyID NOT IN(SELECT CompetencyID
FROM CompetencyGroups WHERE (Deleted = 0) AND (CompanyID = 1) AND (GroupID = 1))) AND
(ParentID = 0) ORDER BY CompetencyName
In SQL I get the list that I need with remaining items not in the group. Now I want to bind this to a DataGrid using EF5.
I cannot get the query syntax properly (Using VB.net) to list the ID and the Name of the Competency...
Converted the provided c# answer to VB:
Dim excludeList = context.CompetencyGroups.Where(Function(x) x.Deleted = False And x.GroupID = GroupID).Select(Function(x) x.CompetencyID).ToArray
Dim results = context.Competencies.Where(Function(c) Not excludeList.Contains(c.CompetencyID) And c.Deleted = False And c.CompanyID = 1 And c.ParentID = 0).OrderBy(Function(c) c.CompetencyName)
GridView2.DataSource = results
GridView2.DataBind()
Hope this helps someone in the future. Took me about 4 hours to search, ask and convert...
Something like
var excludeList = context.CompetencyGroups.Where(x => x....).Select(x => x.CompetencyID).ToArray();
var results = context.Competency.Where(x => !excludeList.Contains(x.CompetencyID));
Update: Somebody else edited this and then someone rejected it, but the edit was a good one (to select the value)
If you need the Cast to make an array of Integers.
Dim excludeList = context.CompetencyGroups.Cast(Of CompentencyGroup).Select(Function(x) x.CompetencyID).ToArray()
Dim results = context.Competency.Where(Function(x) Not excludeList.Contains(x.CompetencyID))
I don't know if this is possible in MS Access, but what I want to do is detect dash (-) and use Between in SQL statement and or Comma.
Ex. I have a table called "Books" with fields: BookID, Title, Subject.
Now how can I query Books table that allows a user to input a value in a textbox like:
1 or 1-5 or 1,3,4.
If the value is 1 the sql statement should be:
SELECT * FROM Books WHERE BookID = 1
If the value of 1-5 then the sql statement should be:
SELECT * FROM Books WHERE BookID BETWEEN 1 And 5
If the value of 1,3,4 then the sql statement should be:
SELECT * FROM Books WHERE BookID IN (1,3,4)
Cut from something I already have;
s = "SELECT * FROM Books WHERE BookID" & parseSarg("11,22,33")
using;
Public Function parseSarg(str As String) As String
Dim re As Object: Set re = CreateObject("vbscript.regexp")
re.Global = True
Select Case True
'//is number
Case reTest(re, "^\d+$", str): parseSarg = " = " & str
'//is number-number
Case reTest(re, "^\d+-\d+$", str): parseSarg = " BETWEEN " & Replace$(str, "-", " AND ")
'//is number,number[,number]
Case reTest(re, "^\d+(?:,\d+)*$", str): parseSarg = " IN (" & str & ")"
'//is >number
Case reTest(re, "^>\s*\d+$", str): parseSarg = " >" & Mid$(str, 2)
Case Else
parseSarg = " = 0 AND 1=0"
End Select
End Function
Function reTest(re As Object, pattern As String, value As String) As Boolean
re.pattern = pattern
reTest = re.Test(value)
End Function
SELECT Books.Title FROM Books WHERE Books.BookID > 1 AND Books.BookID < 5;