简体   繁体   English

如何在这种情况下编写select语句?

[英]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. 我已经在下拉列表中添加了ResorceName和Status以过滤网格现在我的问题是,在这个select语句中,如果任何参数为空,则数据未绑定到网格,但如果我传递了两个参数,则过滤网格和从网格中提供所需的行或过滤的行...任何人都可以告诉我如果任何参数为null,我如何编写select语句。

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. 然而,这不是一个可接受的代码片段,因为它易受SQL注入攻击。 In essence, suppose the ResourceName that is passed in is 实质上,假设传入的ResourceName是

'; 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. 我的建议是始终在.Net中使用SQLCommand对象 - 在其他语言中也称为“Prepared Statements”。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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