简体   繁体   中英

How to write the select statement in this condition?

I have a query which i am using to filter the grid

     SELECT * FROM Resources
              WHERE ResourceName  ='" + ResourceName + "' 
              AND  Status = '" + status + "' "

and my grid looks like this

  ResourceID|ResourceName|Status

I had added the ResorceName and Status in a dropdown for filtering the grid now my problem is that in this select statement if any of the paramaters is null the data is not Binded to the grid but if I pass both the parameters it filters the grid and gives the required row or filtered row from the grid... Can anyone tell me how do I write select statement if any of the parameter is null.

Have a look it the below post on catch all queries

Catch All Examples

In terms of fixing your problem quickly, something like this would work...

Select * From Resources Where (ResourceName = '"+ ResourceName + "' OR ResourceName IS NULL) AND (Status = '" + Status +"' OR Status IS NULL)

That however is NOT an acceptable piece of code, as it is vulnerable to SQL injection. In essence, suppose the ResourceName that is passed in is

'; Drop Table Resources; --

You probably don't need me to tell you what that does.

My advice is to ALWAYS make use of SQLCommand objects in .Net - also known as "Prepared Statements" in other languages. It prevents these kind of tricks...

SELECT * FROM Resources
WHERE (ResourceName  = CASE WHEN '" + ResourceName + "' IS NULL THEN ResourceName  ELSE '" + ResourceName + "' END) //do same for other parameter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM