473,804 Members | 3,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How dynamically create WHERE statement...

I have an advanced search box. The user can type in multiple words in the
box. Those words are then used in the WHERE clause against a Description db
field.

So these words: plumber carpenter electrician

Would essentially equate to: "WHERE (Description LIKE '%plumber%') OR
(Description LIKE '%carpenter%') OR (Description LIKE '%electrician%' )"

Is there any easy way to dynamically create this WHERE clasue? I know how
to do it manually by code, but I didn't know if I had to manually parse the
tokens and construct the clause or if there was an easier way...

(I'm using MySQL.)

Thanks.
Nov 7 '08 #1
12 1423
"Bobby Edward" <bo***@nobody.c omwrote in message
news:um******** ******@TK2MSFTN GP02.phx.gbl...
I have an advanced search box. The user can type in multiple words in the
box. Those words are then used in the WHERE clause against a Description
db field.

So these words: plumber carpenter electrician

Would essentially equate to: "WHERE (Description LIKE '%plumber%') OR
(Description LIKE '%carpenter%') OR (Description LIKE '%electrician%' )"

Is there any easy way to dynamically create this WHERE clasue? I know how
to do it manually by code, but I didn't know if I had to manually parse
the tokens and construct the clause or if there was an easier way...
UNDER NO CIRCUMSTANCES do this!!! Your solution is absolutely wide open to
SQL Injection:
http://www.google.co.uk/search?sourc...L+Injection%22

Instead, allow users to select the occupation(s) they're interested in e.g.
by ticking checkboxes or some other technique - basically, anything to avoid
dynamic SQL...
--
Mark Rae
ASP.NET MVP
http://www.markrae.net

Nov 7 '08 #2


You can read my take on it here:
http://www.sqlservercentral.com/arti...rproblem/2283/

The Zero to N Parameter Problem

"Bobby Edward" <bo***@nobody.c omwrote in message
news:um******** ******@TK2MSFTN GP02.phx.gbl...
>I have an advanced search box. The user can type in multiple words in the
box. Those words are then used in the WHERE clause against a Description
db field.

So these words: plumber carpenter electrician

Would essentially equate to: "WHERE (Description LIKE '%plumber%') OR
(Description LIKE '%carpenter%') OR (Description LIKE '%electrician%' )"

Is there any easy way to dynamically create this WHERE clasue? I know how
to do it manually by code, but I didn't know if I had to manually parse
the tokens and construct the clause or if there was an easier way...

(I'm using MySQL.)

Thanks.

Nov 7 '08 #3
"Mark Rae [MVP]" <ma**@markNOSPA Mrae.netwrote in message
news:us******** ******@TK2MSFTN GP03.phx.gbl...
>
UNDER NO CIRCUMSTANCES do this!!! Your solution is absolutely wide open to
SQL Injection:
http://www.google.co.uk/search?sourc...L+Injection%22

Instead, allow users to select the occupation(s) they're interested in
e.g. by ticking checkboxes or some other technique - basically, anything
to avoid dynamic SQL...
I appreciate that very much Mark. But, what if I want the user to search
for ANY kind of word? It may not be something that I can list.

Can't I just clean up the string, such as by IGNORING the following
words/special characters when I create the WHERE:
DELETE
REMOVE
DROP
SELECT
UPDATE
INSERT
WHERE
*
%
;
..
etc....
Nov 7 '08 #4
"sloan" <sl***@ipass.ne twrote in message
news:ei******** ******@TK2MSFTN GP06.phx.gbl...
>

You can read my take on it here:
http://www.sqlservercentral.com/arti...rproblem/2283/

The Zero to N Parameter Problem
Thanks. I'll check it out! ;)
Nov 7 '08 #5

The url not super "dynamic". But it has a mechanism for parameters.

The previous post is very correct. SQL Injection will mess you up.

"Bobby Edward" <bo***@nobody.c omwrote in message
news:et******** *******@TK2MSFT NGP05.phx.gbl.. .
"sloan" <sl***@ipass.ne twrote in message
news:ei******** ******@TK2MSFTN GP06.phx.gbl...
>>

You can read my take on it here:
http://www.sqlservercentral.com/arti...rproblem/2283/

The Zero to N Parameter Problem
Thanks. I'll check it out! ;)

Nov 7 '08 #6
"Bobby Edward" <bo***@nobody.c omwrote in message
news:%2******** **********@TK2M SFTNGP03.phx.gb l...
I appreciate that very much Mark. But, what if I want the user to search
for ANY kind of word? It may not be something that I can list.

Can't I just clean up the string, such as by IGNORING the following
words/special characters when I create the WHERE:
DELETE
REMOVE
DROP
SELECT
UPDATE
INSERT
WHERE
Absolutely not! Please please read some of the articles in the Google search
I posted.

1=1--;
DECLARE @strSQL nvarchar(100)
SET @strSQL = 'P'+'R'+'I'+'N' +'T ''H'+'E'+'L'+'L '+'O'''
EXEC sp_executesql @strSQL
--
Mark Rae
ASP.NET MVP
http://www.markrae.net

Nov 7 '08 #7
>
Absolutely not! Please please read some of the articles in the Google
search I posted.

1=1--;
DECLARE @strSQL nvarchar(100)
SET @strSQL = 'P'+'R'+'I'+'N' +'T ''H'+'E'+'L'+'L '+'O'''
EXEC sp_executesql @strSQL
I'm using strongly typed XSD datasets with MySql. I thought that simply
replacing all special characters and db words with nothing would suffice,
such as...

strSearch = txtSearchString .text.replace(" +","") ' strip out special
characters
strSearch = strSearch.repla ce("*","") ' strip more
strSearch = strSearch.repla ce("..... ' keep stripping them out
strSearch = strSearch.repla ce("DROP","") ' remove db type words
strSearch = strSearch.repla ce("DELETE","" ) ' remove db type words
strSearch = strSearch.repla ce("SELECT","" ) ' remove db type words
etc etc etc

Then parse what's left using the remaining words/tokens.

Or, maybe I'm too simple minded and am not getting the point. I will do
some more research.

Thanks for your excellent input as usual Mark...
Nov 7 '08 #8
Bobby Edward wrote:
I have an advanced search box. The user can type in multiple words in
the box. Those words are then used in the WHERE clause against a
Description db field.

So these words: plumber carpenter electrician

Would essentially equate to: "WHERE (Description LIKE '%plumber%') OR
(Description LIKE '%carpenter%') OR (Description LIKE '%electrician%' )"

Is there any easy way to dynamically create this WHERE clasue? I know
how to do it manually by code, but I didn't know if I had to manually
parse the tokens and construct the clause or if there was an easier
way...

(I'm using MySQL.)
This may not apply because you're using MySQL, but with SQL Server, you can
use parameterized queries. Parameterized queries allow you to build dynamic
SQL statements that are not susceptible to SQL Injection. You can add
multiple parameters to the command object allowing you to run queries such
as "where x or y or z". The code below is the basic idea ...

SqlCommand cmd = new SqlCommand();

SqlParameter param =
new SqlParameter("@ Description1", SqlDbType.VarCh ar);
param.Value = "%" + "plumber" + "%";
cmd.Parameters. Add(param);

param =
new SqlParameter("@ Description2", SqlDbType.VarCh ar);
param.Value = "%" + "carpenter" + "%";
cmd.Parameters. Add(param);

string Sql =
" SELECT SomeColumns " +
" FROM YourTable " +
" WHERE Description LIKE @Description1 " +
" OR Description LIKE @Description2; ";

SqlConnection conn =
new SqlConnection(" your connection string");

cmd.CommandText = Sql;
cmd.CommandType = CommandType.Tex t;
cmd.Connection = conn;
SqlDataReader sdr = cmd.ExecuteRead er();

--
Ben
http://allben.net/

Nov 7 '08 #9
Thanks Ben. Nice code.

I have XSD strongly typed DataSets that I access thru my Business Layer
code. It accesses MySql but since it's strongly typed doesn't that mean
that I can use the same mechanism with MySql? I'll give it a try.

Thanks again! ;)
Nov 7 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
20405
by: Agoston Bejo | last post by:
I am looking for the PL/SQL equivalent of the VBScript Exec and/or Eval functions, i.e. I want to be able to dynamically create a statement, then execute it in the current PL/SQL context, e.g. declare x integer := 5; begin ExecuteStatement('x := 10'); dbms_output.put_line(x); -- should put "10" if EvaluateExpression('x*2 = 20') then
20
12895
by: David | last post by:
I have a one-line script to add an onunload event handler to the body of the document. The script is as follows: document.getElementsByTagName("BODY").onunload=function s() {alert("s")} Now obviously, I put the alert("s") part in for debugging purposes, just to make sure the error wasn't in any code I was going to be running. This line works just fine in IE6 but in Firefox it doesn't. However, if I replace that line with the...
6
5473
by: Ken Varn | last post by:
I want to add my own custom <STYLE> section in the <HEAD> section of my ASP.NET page within a custom control. Can someone tell me how I can have my custom control add tags to the <HEAD> section of the page dynamically when the page is rendered? -- ----------------------------------- Ken Varn Senior Software Engineer Diebold Inc.
1
1022
by: Reza Nabi | last post by:
Bakground: I have a webform (LoadCtl.aspx) which loads the user control to a placeholder dynamically based on the ctlName querystring passed in the URL. Webform (LoadCtl.aspx) also passes a variable (targetId) in to the usercontrol (IntergySite.aspx) by calling its setter method. Currently, I am using if-then-else and hardcoded the User Control Object to do casting and call the setter method. Question: Is there any way I could load,...
2
1129
by: Andy Sutorius via DotNetMonster.com | last post by:
Hi, I remember in classic ASP when you had a webpage with a large number of textboxes and you needed to perform an update sql statement you could loop through all of the fields and dynamically create a sql statement. I have a webform with over 200 textboxes and I need to perform a sql update. Is there a way to do this in ASP.NET? Thanks,
1
1751
by: keithb | last post by:
I have found that I must re-create dynamically added controls on every postback in order to find and access them programatically. The controls I am working with are inside a GridView control. When the edit button is clicked, a postback occurs and the control are re-created. This causes an additional set of columns to be created in the GridView control, so that all of the dynamically added controls exist in 2 places on the screen. How can I...
9
1868
by: sashang | last post by:
Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict, extra_information): super(MetaThing, cls).__init__(name, bases, dict)
2
1947
by: Suman | last post by:
Happy Friday everyone!!! I am working on a windows service and a C# application and needed some help with certain functionality. Please read through my issue below. Thanks! I have a windows service which writes into a log file periodically (text file). I want to create a windows form application, which, upon invocation should continuously display the contents of the log file. Even the newly made entries into the log file while the...
2
3390
by: jmarendo | last post by:
Hello, After reading through the "Table Basics - DOM - Refer to table cells" example at mredkj.com , I modified the code for my own purposes. In the modified version, I create a hyperlink and place it in the last cell of each row that I create dynamically using DOM methods. Everything is working well (that is, just like the original example) except for something related to the function behind my link. The link simply calls a function...
1
7554
Merlin1857
by: Merlin1857 | last post by:
How to search multiple fields using ASP A major issue for me when I first started writing in VB Script was constructing the ability to search a table using multiple field input from a form and having the sql statement dynamically built according to the input provided by the user. I have used the method described here hundreds of times it is quick and adaptive. I generally use a frames page for the search, in this way the search is maintained...
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9572
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10070
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.