ASP.NET GridView查询中的通配符

时间:2009-03-11 02:40:25

标签: asp.net sql gridview

我在ASP.NET 2.0中使用GridView。我想根据我的搜索crieteria(访客姓名,护照号码,公司名称)在GridView中显示3个表格(SQL2005)的详细信息。它正在工作,但我想使用通配符搜索“访客姓名”的第一个字母。我在GridView的QueryBuilder中使用我的代码(使用配置数据源)。查询如下:

SELECT FormMaster.NameofCompany, VisitorMaster.NameofVisitor,
VisitorMaster.PassportNumber, FormMaster.FormID,  
VisitorMaster.VisitorID FROM VisitorMaster INNER JOIN VisitorDetails ON
VisitorMaster.VisitorID = VisitorDetails.VisitorID INNER JOIN FormMaster ON
VisitorDetails.FormID = FormMaster.FormID WHERE (FormMaster.FormStatusID = 1) AND
(VisitorMaster.PassportNumber = @PassportNumber ) OR
(VisitorMaster.NameofVisitor = @NameofVisitor) OR
(FormMaster.NameofCompany = @NameofCompany )

3 个答案:

答案 0 :(得分:1)

您的查询是:

SELECT
  FormMaster.NameofCompany,
  VisitorMaster.NameofVisitor,
  VisitorMaster.PassportNumber,
  FormMaster.FormID,
  VisitorMaster.VisitorID
FROM
  VisitorMaster INNER JOIN VisitorDetails ON
    VisitorMaster.VisitorID = VisitorDetails.VisitorID
  INNER JOIN FormMaster ON VisitorDetails.FormID = FormMaster.FormID
WHERE
  (FormMaster.FormStatusID = 1) AND
  (VisitorMaster.PassportNumber = @PassportNumber ) OR
  (VisitorMaster.NameofVisitor = @NameofVisitor) OR
  (FormMaster.NameofCompany = @NameofCompany )

你确定它运作正常吗?当FormMaster.FormStatusID不等于1且最后两个条件之一为真时,它仍将返回该行。在TSQL中,AND的优先级高于OR

正确地,您的WHERE条款应为:

FormMaster.FormStatusID = 1 AND (
  VisitorMaster.PassportNumber = @PassportNumber OR
  VisitorMaster.NameofVisitor LIKE @NameofVisitor OR
  FormMaster.NameofCompany LIKE @NameofCompany)

并将%附加到您传入的@NameofVisitor和@NameofCompany参数。按照Shawn或WebMatrix建议的方式执行此操作,如果您未传入某些内容,则会匹配所有内容,而LIKE''仅匹配空字符串。

答案 1 :(得分:0)

VisitorMaster.NameofVisitor,如@NameofVisitor +'%'

答案 2 :(得分:0)

试”  NameOfVisiotr 喜欢'A%'而不是