Taking User Input in SQL SELECT TOP query - sql

I need to acquire the sum of the least n number of values from a table
Dim lot As String = "SELECT SUM(x2) AS x3 FROM (SELECT TOP '" & _TextBox2.Text & "' x1 As x2
FROM (
SELECT SharePrice As x1
FROM Shares
WHERE(Company = '" & _TextBox1.Text & "' AND Availability = True)
ORDER BY SharePrice ASC )
)"
I dont have problems witha nything else but the TOP '" & _TextBox2.Text & "' part
Does the SELECT TOP really take parameters in?
I can replace the textbox reference with a hard coded integer and it works. But i want to make it run In visual Basic with user input

You cannot use single quotes around the number in the TOP n portion of the query.
Change:
SELECT TOP '" & _TextBox2.Text & "'
To:
SELECT TOP " & _TextBox2.Text & "
I also recommend that you use a parametrized query to help prevent SQL Injection.

It's a lot easier to do this as a parameterized query. In addition to preventing sql injection attacks it avoids the problems of when to put quotes around things.
In order to get Top to work you will need to surround the parameter name with parens
Dim lot As String = " SELECT SUM(x2) AS x3
FROM
(SELECT TOP (#Top) x1 As x2
FROM (SELECT
SharePrice As x1
FROM Shares
WHERE
(Company = #CompanyName
AND Availability = True)
ORDER BY SharePrice ASC ))"
Dim cmd as SqlCommand = new SqlCommand (connection, lot)
cmd.AddWithValue (#Top, Int32.Parse(_TextBox2.Text))
cmd.AddWithValue (#CompanyName, _TextBox1.Text)

Related

MS Access VBA SQL SELECT * INTO tempTbl WHERE Stuff="" AND OtherStuff BETWEEN Date Range

I have a form with one text box, two combo boxes (dropdowns), and two text boxes with input masks for mm/dd/yyyy 99/99/0000;0;_
I am attempting to use all of these fields as filters for a subform.
I have the controls set to fire after update and run a sub that builds a SELECT * INTO sql string for a temp Table that is then sourceobject'ed back to the subform.
In code I have for each control I have code building a snippet of the Where statement for the final sql. the snippet grows as needed, is labeled "Filter"
Some other non-Finished Code....
If Not IsNull(txtDateFrom) Then
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= " & Me.txtDateFrom & ")" & " And " & "([Date_LastSaved] <= " & Me.txtDateTo & ")"
End If
Dim sql As String
sql = "SELECT * INTO tmpTable FROM tblReview"
If Not IsNull(Filter) Then
sql = sql & " WHERE " & Filter
End If
My issue and question is that I am testing this one specific situation where there will be Filter = Filter & " AND " & "DATE_STUFF"
where the final sql looks like...
SELECT * INTO tmpTable FROM tblReview WHERE ReviewStatus = 'Quoted' AND ([Date_LastSaved] >= 09/12/2018) And ([Date_LastSaved] <= 10/16/2018)
which should have some result with the test data. Yet, the tmpTable is empty.
This is only happening when I apply a date range criteria.
I tried BETWEEN but could not nail down the syntax.
Any insight is greatly appreciated, Thanks!
UPDATE:
Answer:
If i > 1 Then Filter = Filter & " AND " & "([Date_LastSaved] >= #" & Me.txtDateFrom & "#)" & " And " & "([Date_LastSaved] <= #" & Me.txtDateTo & "#)"
If you want to use dates then they must be quoted. If you just say 10/16/2018 then you are dividing the integer 10 by 16 by 2018 which will yield an integer zero. It will then convert the dates to an integer to do the compare, which will yield a much bigger number, and thus you get no rows.
Any date testing should always be done using date types rather than strings. I think in msaccess you can surround it in #, but not sure. Just research this.

Error in SQL query expression

I´m trying to run the following SQL code on access 2010, but it returns syntax error in query expression. Any ideas what could be causing it?
Thanks in advance.
DELETE FROM Trn_done
WHERE (Trn_done.training =
SELECT Training
FROM Trainings
WHERE (Trainings.Area = '" & Area & "'))
The bracket should be before the nested SQL as mentioned below
DELETE FROM Trn_done
WHERE Trn_done.training IN (
SELECT Training
FROM Trainings
WHERE (Trainings.Area = '" & Area & "')
)
You shouldn't EQUAL a select statement, lest multiple rows in your select cause your code to break. Try this instead:
DELETE td
from Trn_done td
inner join Trainings t
on td.training = t.training
WHERE t.Area = '" & Area & "'

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("'", "''"))

String or binary data would be truncated. The statement has been terminated

I always got an error when adding a new data. the error says
String or binary data would be truncated. The statement has been terminated
As I've looked back on my backend or code. It looks like there's a conflict adding a TWO LABEL DATA in one column because I would like to join the (Year)-(StudentNumber)
Here's the code of my INSERT INTO Statement
INSERT INTO
[Student_Information] (StudentID, LastName, FirstName, MiddleName, Gender,
ContactNumber, Citizenship, Religion, Birthday, Address)
VALUES
( '" & lbl_cyear.Text - studid.Text & "','" + txt_lname.Text + "', '" + txt_fname.Text + "', '" + txt_mname.Text + "', '" + DDGender.Text + "', '" & txt_cnumber.Text & "', '" & txt_citizenship.Text & "' , '" + txt_religion.Text + "' , '" & txt_bday.Text & "', '" & txt_address.Text & "' )"
and here's the code how I generate the Year and the Student Number
Sub SNYear()
Dim test As Date
test = Convert.ToDateTime(Today)
lbl_cyear.Text = test.Year
End Sub
Sub SNGenerate()
'displaying Studentid
Dim SN As Integer ' Student Number
Dim SID As String 'Student ID Num as String
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "Select Max (StudentID) as expr1 from [Student_Information]"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
End If
If rdr.Item(0).ToString = Nothing Then
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
ElseIf rdr.Item(0).ToString = 0 Then
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
Else
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
End If
studid.Text = SID
cmd1.Connection.Close()
End Sub
Can someone help me with the code? How to join 2 data in different label text and save it to one column in my table.
Woah! Never ever write sql queries like that. It's subject to dangerous SQL injection, and code like that is actually used as worst-case scenarios in SQL injection lectures everywhere!
That being said, the error message String or binary data would be truncated. The statement has been terminated. actually spells out what is wrong. You are trying to insert too much data into a field that has a specific dimension.
You are trying to insert the following expression into the StudentID field:
lbl_cyear.Text - studid.Text
I'm not even sure what you want to do there. Since Visual Basic is loosely typed by default, It will probably handle the lbl_cyear.Text as a number and try to subtract the studid.Text (as a number) from it. You probably mean something like this:
lbl_cyear.Text & "-" & studid.Text
It seems you are trying to use the StudentID column for two different types of information. Don't do that. Decide on one format for the student ids and dimension the column for it.
Is this a homework assignment?
Y#atornblad has some very valid points about re-structuring your code. However, the specific problem you are asking about is likely because you are trying to insert data into a column that is longer than the column can accept.
E.g. - you are trying to insert "Lorem Ipsum" into a column that has a maximum length of 5 characters.
Edit
You need to take another look at how your table is defined and make sure it is appropriate for the data you are storing. Also - make sure the data you are trying to store is in the correct format that the table was designed for. Don't assume it's in the format you want, actually step through the program in debug mode and look at what the variable is before it gets sent to the database.

VBA sql query problem

Below query is resulting NO rows
lstResults.RowSource = "select EmpId from tblTesting where Empid ='" & Me.txtSearchEmpId.Value & "'"
Where below working fine :
lstResults.RowSource = "select * from tblTesting"
WHere is the fault here?
I check the value of '" & Me.txtSearchEmpId.Value & "'" using break point its having the value of "123" (numerical)
My empid is numerical value
Please help
If your EmpId is numerical, you probably want to remove the single-quotes:
lstResults.RowSource = "select EmpId from tblTesting where Empid = " & Me.txtSearchEmpId.Value
How does that work?
First, remove the single quotes from around your value, if it really is a number.
Second, cleanse your input. What if someone types 123 or true into your input field? You've then let them select all inputs. You might want to convert the value to an integer and then back to a string to make sure it is pure.
See xkcd #327: