ASP.NET passing value from textbox to selectcommand with IN vb - sql

I have an asp.net webpage with an asp.net gridview with the following query:
SelectCommand="SELECT * from details2 as t2 WHERE (t2.OCC IN ('+ #txtCOUNTRY +') OR t2.DCC IN ('+ #txtCOUNTRY +')) and t2.ac='Y'"
The textbox txtCOUNTRY value can have the following values (for example):
'AR','ES'
However the parameter #txtCOUNTRY doesn't seem to be properly, written as the gridview shows nothing.
if I change it to (for example) it works:
SelectCommand="SELECT * from details2 as t2 WHERE (t2.OCC IN ('AR,'ES') OR t2.DCC IN ('AR','ES')) and t2.ac='Y'"
So I can only assume the #txtCOUNTRY parameter is incorrectly written.
Any ideas ?

When you pass the values 'AR','ES' via a SQL parameter, they will automatically be escaped which would make your query literally look for the value: 'AR','ES'.
See this: Parameterize an SQL IN clause
So in your case (since you have a comma separated list of values, each in single quotes):
SelectCommand = "SELECT * from details2 as t2 WHERE " &
"(','+#txtCOUNTRY+',' LIKE '%'','+t2.OCC+''',%' OR ','+#txtCOUNTRY+',' LIKE '%'','+t2.DCC+''',%') " &
"and t2.ac='Y'"
If you are not enclosing your values in single quotes (for example: AR,ES) then the query becomes a bit more readable as you are not having to escape the single quotes in your query:
SelectCommand = "SELECT * from details2 as t2 WHERE " &
"(','+#txtCOUNTRY+',' LIKE '%,'+t2.OCC+',%' OR ','+#txtCOUNTRY+',' LIKE '%,'+t2.DCC+',%') " &
"and t2.ac='Y'"
Edit to provide some clarity as to why this works.
So for example, providing AR,ES as the value for the #txtCOUNTRY parameter would yield a condition:
,AR,ES, LIKE *,[t2.OCC],* OR ,AR,ES, LIKE *,[t2.DCC],*
This condition would be a match if either t2.OCC or t2.DCC were either AR or ES because the pattern would be matched.
This provides a simple way to pass in a comma separated list as a parameter so your query isn't exploitable with a SQL injection.

Related

Dynamically create sql where condition on textbox entry

I am working on a C# desktop application. I want to create a search functionality. Now the problem is that i am using around 8 textboxes. Different permutations of textboxes could be populated and the resulting 'sql where' condition should only include those textboxes values which are not null. Now one pathetic way is to use a zillion 'if and else' which obviously is laborious. Any other way to do this?
You need just one query with filled WHERE to use all parameters like this
select ...
from ...
WHERE
(firstNameColumn=:firstNameParam or :firstNameParam is null)
AND (lastNameColumn=:lastNameParam or :lastNameParam is null)
AND (...)
I would like to make a point of first checking is the paramtere null, then use it to compare with column values.
Since you are generating query in C#, try old-Chinese approach from Ming period of using default condition where 1=1 just to avoid checking did you already had first condition :)
string query = "select ... from ... join ... on ... where 1=1";
//suposedly you have value of one search box in variable called "item_name"
if(string.IsNullOrWhiteSpace(item_name) == false)
{
query += " and Order_Line.Name ='" + item_name + "'";
}
and so on for other fields.
What you are trying to do in order to avoid ifs is not really a good approach. Look at this:
string query = " select ... where Order_Line.Name = '" + item_name + "'";
What will be the resulting string if item_name is actually null?
EDIT: the resulting query would be
where Order_Line.Name = '' or Order_Line.Name is null
which is not what you want. You want every row if that search field is empty, menaing it shouldn't have anu effect on search. That's why you need condition to see will you include this column in where clause in the first place.

Use an Access Forms Unbound text box as a Field filter in a table

Access 2013 - Reference an Unbound text box on a Form
I am currently trying to use an unbound text box [Text161] on a Form name [DCM_Gap_Servers] to sort information through a table. I want the query that I created to be able to take the users input from [DCM_Gap_Servers]![Text161] as the field that is being sorted from the table names 'Server'.
This is the SQL I am using right now in the query:
SELECT * FROM Servers WHERE "Forms![DCM_Gap_Servers]![Text161]" IS NULL
** I have already Tried:
"Forms![DCM_Gap_Servers]![Text161]" ; (Forms![DCM_Gap_Servers]![Text161]); Forms.[DCM_Gap_Servers]![Text161]
This will work at any time if I replace the Text Box reference with the actual Field name I am using, but since there are hundreds of combinations of fields, I need the reference to work.
I have looked all over, and I can't seem to find the correct answer. I am willing to do it in VBA if needed, whatever it takes to get the filtering done correctly.
Thank You.
It is:
SELECT * FROM Servers WHERE Forms.[DCM_Gap_Servers].[Text161] IS NULL
but that will just select all records whenever your textbox is Null.
So it rather is:
SELECT * FROM Servers WHERE SomeField = Forms.[DCM_Gap_Servers].[Text161]
To use the form value as a field name, you must use concatenated SQL:
strSQL = "SELECT * FROM Servers WHERE " & Forms![DCM_Gap_Servers]![Text161].Value & " IS NULL"
This you might pass to the SQL property of an existing query object:
MyQueryDef.SQL = strSQL
Or:
Constant SQL As String = "SELECT * FROM Servers WHERE {0} IS NULL"
FieldName = Forms![DCM_Gap_Servers]![Text161].Value
MyQueryDef.SQL = Replace(strSQL, "{0}", FieldName)
Of course, take care the the field name isn't a zero length string.

Matching text string on first letter in SQL query

SAMPLE CODE:
Dim sql As String = "SELECT * FROM " + tblName + " WHERE needsTranslation = 'True' AND dataText LIKE " & "'" & alpha & "%" & "'" & " ORDER BY dataText;"
da = New SqlDataAdapter(sql, strConnection)
OP:
I would like to create a SQL query that returns all records when the first letter of a string matches my variable. I am coding this in an ASP.net code behind page in vb.net.
SELECT * FROM " + tblName + " WHERE textData = ' & alpha & "
In this exmample textData is a string of text and alpha is a single letter a through z or A through Z.
I don't need the criteria to be case sensitive, but I do need only the first letter of textData to match alpha.
I have tested the LIKE comparator and it does not return all records that begin with alpha.
What is the best way to do this? Any and all help will be appreciated.
thanks again,
The LIKE operator is what you'd want to use, but you have to use the % wildcard character like so:
SELECT * FROM MyTable WHERE textData LIKE 'a%'
SQL has sub-string operator SUBSTR() or SUBSTRING()
select * from tableName where substr( textData ) in ( 'A', 'B', 'C', ... );
I couldn't add to the comments on one of the other posts, but I'll strongly second the need to use a parameterized query for these reasons (you can include usage of the like operator with the wildcard % like the other answer correctly summarized to answer your question):
It will protect you from making mistakes with single quotes, especially if the user enters a search string that includes them
(they will cause your query to fail).
It protects you from SQL injection exploits. Example, a user were able to input the value of the variable "alpha" in the above
example they could enter something like:
'; DELETE FROM ;
If the user you were using had excessive database rights, they could
wreak all kinds of havoc (or they could potentially get access to
data they shouldn't have access to).

Split a String in Microsoft Access SQL for use with a command parameter

I am using Microsoft Access 2000, and need to pass in a parameter that is a comma-delimited string. The comma-delimited string is for an IN clause of the where statement. An example of this would be:
SELECT * FROM Table1 WHERE Field1 IN (#MyValues)
where #MyValues might be something like 1,2,3
However, when I pass in 1,2,3 the Access parameter doesn't seem to accept the input. Is there a good split string function in Access SQL that will solve this issue? Or is there another way of tackling this problem?
For reference on what I am doing, I am trying to use parameterized SQL in .NET to get a result set.
EDIT:
Below is an example of some simplified .NET code that would call this query:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Table1 WHERE Field1 IN (#MyValues)");
cmd.Parameters.Add("#MyValues","1,2,3");
What about this:
SELECT * FROM Table1 WHERE #MyValues Like "%" & Field1 "%"
This should check to see if the value in the field is included as a substring of your #MyValues parameter. Now, this could be problematic if any of the individual values in #MyValues are substrings of each other:
SELECT * FROM Table1 WHERE "2, 5, 10" Like "%" & Field1 "%"
In that case, "1" in Field1 would match, but it shouldn't. So, it might be that you'd need to format the numbers or delimit them some other way, such as:
SELECT * FROM Table1 WHERE " 2 5 10 " Like "% " & Field1 " %"
Or, alternatively:
SELECT * FROM Table1 WHERE ", 2, 5, 10," Like "%, " & Field1 ",%"
I'm not sure how this would perform, but it at least would allow parameterization.
At first, your question looked a little familiar. Then it started looking REALLY familiar. Then I realized I had the same question not long ago. My solution was to toss the parameters into this function:
Public Function IsIn( _
ByVal value As Variant, _
ParamArray theset() As Variant) _
As Boolean
Dim i As Long
For i = LBound(theset) To UBound(theset)
If value = theset(i) Then
IsIn = True
Exit Function
End If
Next
End Function
In your sample SQL code, you could do something like:
SELECT * FROM Table1 WHERE IsIn(Field1,array(1,2,3))=true;
(Like you, I also think that a procedure like this one should have been built into Access. Perhaps it is in 2007 or 2010.)
Edit
See Is there a NotIn("A","B") function in VBA?
Can you put them in another table and do a join?
If you don't want to create another table, that's ok. What does your ADO code and query syntax look like?
From your edited code above, I don't think you need to use the cmd object's parameters collection. Just modify your sql to embed your parameter values:
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Table1 WHERE Field1 IN (1,2,3)");
You would use the .parameters collection if you had a parametrized query in the mdb, which you don't. Your sql is in source code.

SQL concatenation inside VBA string

I'm using VBA excel 2003,SQL 2005 to make a sql query call and inside my sql statement I'm using '+' operator to concatenate two strings.
dim query as string
query = "Select distinct ', '+emailaddress1 "
query = query & "from contact "
would this work inside vba? My query returns too many records in excel but not in SQL?
Please just focus on this 2 lines of code and not worry about the rest of my sql call, I'm just wondering whether or not this specific string would work?
Your code will return a column where each row would be an email address with a comma in front of it. If that is what you want, then yes, it will work.
If, on contrary, you want a single string where all email addresses would be listed, separated with commas, that'd be
query = "declare #foo varchar(max);"
query = query & "select distinct #foo = isnull(#foo,'') + emailaddress1 + ', ' from contact;"
query = query & "select left(#foo, len(#foo)-2);"