Select Command with Multiple LIKEs

╄→гoц情女王★ 提交于 2019-12-24 00:32:46

问题


Functionality

User inputs text into textboxA. Search the database records for First Names AND Last Names corresponding to the user's input.

The Problem:

It appears the results I am getting are only searching "First Name" field and not BOTH the First Name and Last Name Fields

Example:

*A search for "Mike" returns:*

Mike Smith

Mike Jones

A search for "Jones":

Mike Jones is not returned

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

Code Explanation:

txtSearch is the user's search input


回答1:


Change

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

to

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)



回答2:


Below is the SQL query with the WHERE clause adjusted to give you the flexibility to search by only first name, only last name, or both.

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)

With this query I'm making the assumption that if the user searches for FirstName: "Mike" and LastName: "Jones" that the search results should only contain "Mike Jones", not "Mike Smith", "Mike Jones", and "Paul Jones".

Note that if you use this approach, you will need to make sure not to populate your parameters with an empty string in the case where the user did not supply a value for a criteria. Alternatively, you could check for empty strings in the query in addition to null.



来源:https://stackoverflow.com/questions/13373159/select-command-with-multiple-likes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!