选择具有多个LIKE的命令

时间:2012-11-14 04:40:03

标签: asp.net sql search select gridview

功能

用户将文本输入到textboxA中。 在数据库记录中搜索与用户输入相对应的名字和姓氏。

问题:

看来我得到的结果只是搜索“名字”字段而不是名字和姓氏字段

示例:

* 搜索“Mike”会返回: *

迈克史密斯

迈克琼斯

搜索“琼斯”:

Mike Jones未被退回

CODE:

Protected Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles button1.Click

    If txtSearch.Text = "" Then

    Else

        Dim ConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("oakfratintdbConnectionString").ConnectionString
        Dim Conn As New SqlConnection(ConnString)
        Dim searchCMD As New SqlCommand("SELECT [FirstName], [LastName], [MidInitName], [NameSuffix], [NamePrefix], [DOB], [DOD], [BurialDate], [GeoDirection], [Space], [Lot], [Row], [IntermentSpec], [AddtlInfo] FROM [OFCInterments] WHERE ([FirstName] LIKE @FirstName)", Conn)
        Dim searchDT As DataTable = GetData(searchCMD)
        GridView1.DataSource = searchDT
        GridView1.DataBind()
    End If

End Sub

代码说明:

txtSearch是用户的搜索输入

2 个答案:

答案 0 :(得分:3)

更改

SELECT [FirstName], [LastName], [MidInitName], [NameSuffix], [NamePrefix], [DOB], 
[DOD], [BurialDate], [GeoDirection], [Space], [Lot], [Row], [IntermentSpec], 
[AddtlInfo] FROM [OFCInterments] WHERE ([FirstName] LIKE @FirstName)

SELECT [FirstName], [LastName], [MidInitName], [NameSuffix], [NamePrefix], [DOB], 
[DOD], [BurialDate], [GeoDirection], [Space], [Lot], [Row], [IntermentSpec], 
[AddtlInfo] FROM [OFCInterments] WHERE ([FirstName] LIKE @FirstName or 
LastName like @LastName)

答案 1 :(得分:1)

下面是调整了WHERE子句的SQL查询,使您可以灵活地仅使用名字,只搜索姓氏或两者兼而有之。

SELECT [FirstName], [LastName], [MidInitName], [NameSuffix], [NamePrefix], [DOB], [DOD], [BurialDate], [GeoDirection], [Space], [Lot], [Row], [IntermentSpec], [AddtlInfo] FROM [OFCInterments] WHERE
    (@FirstName IS NULL OR [FirstName] LIKE @FirstName)
    AND (@LastName IS NULL OR [LastName] LIKE @LastName)

通过这个查询,我假设如果用户搜索FirstName:“Mike”和LastName:“Jones”,搜索结果应该只包含“Mike Jones”,而不是“Mike Smith”,“Mike Jones” “,和”保罗琼斯“。

请注意,如果您使用此方法,则在用户未提供条件值的情况下,您需要确保不使用空字符串填充参数。或者,除了null之外,您还可以在查询中检查空字符串。