SQL/ACCESS Get Value From Previous Row - sql

Ok, so sweet and short. I'm writing a Forms App in VB and I'm connected to an ACCESS file. I need to get the value from the first select statement and use it in the second select statement. I know I can do this through the application itself but I'm looking to do it this way. Thanks in advance.
Dim cmd As New OleDbCommand(
"SELECT SSClass AS result
FROM Members
WHERE Names = '" + lstBoxMembers.SelectedItem.ToString() + "'
UNION
SELECT Names FROM Members WHERE SSClass= result ", conn)

Related

String.Format vs Parameter Values SQL Query

I'm trying to figure out if there is a better way to do this
Dim cmd As New SqlCommand
Dim sel As String
Dim obj As New DataHandler
sel = String.Format("SELECT * FROM Customers WHERE Country LIKE '{0}%'", txt_Input.Text)
cmd.CommandText = sel
Me.dgv_Customers.DataSource = obj.SqlDataRetriever(cmd)
Basically what im trying to do is have a textbox that whenever I type a letter, the grid refreshes itself by sending a Query to my SQL server searching for whatever its in the textbox using the LIKE() from SQL. I've been reading about SQL injection and so far everyone suggests to use parameter values (#value) for user input, but if I try to replace the {0} with that it doesn't work. I just wanna make sure that this is a valid way of doing this.
Thanks
Instead just concatenate the string like below. You should consider using parameterized query to avoid SQL Injection.
sel = "SELECT * FROM Customers WHERE Country LIKE '" + txt_Input.Text + "%'";
Use a parameterized query rather. See This Post
Dim cmd as New SqlCommand("SELECT * FROM Customers WHERE Country LIKE #param")
cmd.Parameters.Add("#param", txt_Input.Text +"%")

Pass parameter to a query from another query in Access

I have a parameterized query GET_CUSTOMER:
SELECT * FROM Customer WHERE id = [customer_id]
I want to call this query from another query and pass it a parameter:
SELECT * FROM GET_CUSTOMER(123)
Note the above code is not valid, it is here to give you an idea of what I'm trying to do. Is it possible to do this in MS Access?
UPDATE 1:
The queries I posted are for example. The actual queries are much more complex. I know I can use table joins, but in my specific case it would be much easier if I could run parameterized queries inside other queries (that are parameterized as well). I can't use access forms because I'm using access with my .NET application.
This is how I end up solving this with help of https://stackoverflow.com/a/24677391/303463 . It turned out that Access shares parameters among all queries so there is no need to specifically pass parameters from one query to another.
Query1:
SELECT * FROM Customer WHERE ID > [param1] AND ID < [param2]
Query2:
SELECT * FROM Query1
VB.NET code:
Dim ConnString As String = "Provider=Microsoft.Jet.OleDb.4.0;Data Source=Database.mdb"
Dim SqlString As String = "Query2"
Using Conn As New OleDbConnection(ConnString)
Using Cmd As New OleDbCommand(SqlString, Conn)
Cmd.CommandType = CommandType.StoredProcedure
Cmd.Parameters.AddWithValue("param1", "1")
Cmd.Parameters.AddWithValue("param2", "3")
Conn.Open()
Using reader As OleDbDataReader = Cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader("ID"))
End While
End Using
End Using
End Using
You can build the SQL on the fly.
MyID = prompt or get from user some ID
strSQl = "Select * from tblCustomer where ID in " & _
"(select * from tblTestCustomers where id = " & MyID
So you can nest, or use the source of one query to feed a list of ID to the second query.

MS Access SELECT query DatePart

i have some problem with my SELECT Query to MS Access .mdb file.
i am using VB.Net and have to send query like..
"SELECT d_date, d_tons, d_qty, d_cost FROM [deal] WHERE DatePart(""m"", [d_date]) = '" _
+ DTP.Value.Month.ToString + "' AND ([d_client] = '" + cBoxClient.Text + "')"
But it doesn't work.. No Error in compiling but this Query cannot SELECT any data.
DTP is DateTimePicker, i select Month with DTP and filled some text into cBoxClient(ComboBox)
What's wrong with that Query? i have no idea because i always used MySQL and this is my first application development with MS Access..
Please HELP me.
Use parameterized query, that will save you from sql injection and complexity of converting specific data format (such as DateTime) to it's string representation that is valid according to database specific culture. For example :
Dim queryString = "SELECT d_date, d_tons, d_qty, d_cost FROM [deal] WHERE " & _
"DatePart(""m"", [d_date]) = ? AND ([d_client] = ?)"
OleDbCommand cmd = New OleDbCommand(queryString, connection)
cmd.Parameters.AddWithValue("#date", DTP.Value.Month)
cmd.Parameters.AddWithValue("#client", cBoxClient.Text)

Select all data from 1 column

I have code that is supposed to take all "course names" from a module based on what school is chosen.
For example the school of biology has the modules "biochemistry" and "marine biology". I need to select both of these in order to use in a calculation.
Currently when the code is run it will only take the first module ie "biochemistry" but I need it to select all of the modules.
Can anyone help?
Dim courseSelectCom As New SqlCommand("SELECT course_name FROM course where school= '%"schoolSelect & "' ", _
connection)
The first thing to do on your query is to use a parametrized query.
This will avoid Sql Injection and parsing problems.
Then you shoud explain why you use the wildcard % in front of SchoolSelect.
Do you have many kind of schools that ends with the same suffix and do you want to retrieve all of them?
Last, you should use a DataReader to loop over the returned data or a DataAdapter to fill a DataTable.
So summarizing
Dim sb = new StringBuilder()
Using connection = New SqlConnection("your_con_string_here")
connection.Open()
Dim courseSelectCom = New SqlCommand("SELECT course_name FROM course where school=#schoolName", connection)
courseSelectCom.Parameters.AddWithValue("#schoolName", SchoolSelect.Text)
Dim reader = courseSelectCom.ExecuteReader()
while reader.Read()
sb.AppendLine(reader("course_name")) ' or add to some kind of list to reuse'
End While
End Using
Console.WriteLine(sb.ToString())
if you want to store the data in a DataTable then replace the DataReader loop with
Dim dt = New DataTable()
Dim da = New SqlDataAdapter(courseSelectCom)
da.Fill(dt)
And you have a DataTable object to use for binding to a DataGridView, Listbox or whatever....
What are you using for Executing the command?
If you use ExecuteScalar you will get only first result.
Use ExecuteReader and read through or Use DataAdapter and fill a DataSet with it.
Dim courseSelectCom As New SqlCommand("SELECT course_name FROM course where school=#School", _connection)
courseSelectCom.Parameter.Add("#School", SqlDbType.VarChar).Value = SchoolSelect.Text
SchoolSelect is the textbox from which you select school
If you want all the courses in a comma delimited list, then use group_concat (assuming you are using MySQL):
SELECT group_concat(course_name)
FROM course
where school= '%"schoolSelect & "'
This returns one row, with all the courses in a single column, like 'biochemistry,marine biology'.
To do this in SQL Server, you can do:
select stuff((select ','+course_name from course where school= '%"schoolSelect & "' for xml path ('')),
1, 1, '') as coursenames
SQL Server does not have a native aggregate string concatenation operator, so this uses XML features of the database.
I think it would be written as:
Dim courseSelectCom = New SqlCommand("select stuff((select ','+course_name from course where school= '%"schoolSelect & "' for xml path ('')), 1, 1, '') as coursenames", connection)
You need something like this:
Dim reader = courseSelectCom.ExecuteReader()
reader.Read()
reader("course_names")

VB.NET 2010 & MS Access 2010 - Conversion from string "" to type 'Double' is not valid

I am new to VB.Net 2010. Here is my problem: I have a query that uses a combo box to fetch many items in tblKBA. All IDs in the MS Access database are integers. The combo box display member and value member is set to the asset and ID of tblProducts.
myQuery = "SELECT id, desc, solution FROM tblKBA WHERE tblKBA.product_id = '" + cmbProducts.SelectedValue + "'"
In addition to getting items from the KBA table, I want to fetch the department details from the department table, possibly done in the same query. I am trying to do it in two separate queries.
myQuery = "select telephone, desc, website from tblDepartments where tblDepartments.product_id = tblProducts.id and tblProducts.id = '" + cmbProducts.SelectedValue + "' "
All help will be appreciated!
Change the '+' to a '&' then the compiler would be happy.
try adding .toString to cmbproducts.selectedvalue or do "tblKBA.product_id.equals(" & cmbProducts.selectedValue.toString & ")"
1.) Don't use string concatenation to build your query. Use parameters.
2.) I am guessing that tblKBA.product_id is a double and not a string, so don't put quotes around it.
myQuery = "SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = ?"
3 things. Test your value before building the select statement. Second, Use .SelectedItem.Value instead of .SelectedValue. Third, protect yourself from sql injection attack. Use parameters, or at the very least check for ' values.
If IsNumeric(cmbProducts.SelectedItem.Value) = False Then
'No valid value
Return
End If
myQuery = String.Format("SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = {0}", cmbProducts.SelectedItem.Value.Replace("'", "''"))