Search code examples
asp.netsql-servertable-relationships

Get results from two tables - asp.net/SQL Server 2008R2


I have a search form with 2 fields(first name and last name) from one table (Just has person's information) and 4 (Incident number, date, place, created by) from the other (has one or more incidents for the person in the first table) linked through foreign key(nameID). I think the problem is what kind of join to use and how to use the WHERE clause.

Thanks.

More information: @Tim - Isn't the user input into one or more fields the filter or it is the WHERE Clause? The user doesn't have to fill in all the fields. Thats where I am getting lost. The user is trying to find the incident to update it. Does this help?

Also I have to use "Like%LName%" in the Where clause to get all the names if they don't enter the entire name.

My query looks like this:

Protected Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
    Dim strSearch As String
    strSearch = "SELECT tblPatron.LName, tblPatron.FName, tblIncident.CreatedBy, "
    strSearch = strSearch + "tblIncident.Inci_ID, tblIncident.Inci_date, tblIncident.Inci_type, tblIncident.Library, "
    strSearch = strSearch + "tblIncident.PatronName, tblIncident.Location "
    strSearch = strSearch + "FROM tblPatron INNER JOIN tblIncident ON tblPatron.PatronID = tblIncident.PatronID "
    strSearch = strSearch + "WHERE "
    strSearch = strSearch + "(tblPatron.LName Like '%" + txtLName.Text.ToString() + "%') "
    strSearch = strSearch + "AND (tblPatron.FNAME Like '%" + txtFName.Text.ToString() + "%')"
    strSearch = strSearch + "AND (tblIncident.Inci_ID ='" + strInciNum.Text.ToString() + "')"
    strSearch = strSearch + "AND (tblIncident.Inci_date = '" + txtInciDate.Text.ToString() + "')"
    strSearch = strSearch + "AND (tblIncident.Inci_type = '" + ddInciCat.SelectedValue.Trim + "')"
    strSearch = strSearch + "AND (tblIncident.Library = '" + ddLib.SelectedValue.Trim + "')"
    SearchPDS.SelectCommand = strSearch
    SearchPDS.DataBind()
    GridSearchResults.DataBind()
    GridSearchResults.Visible = True
End Sub

Solution

  • I took the suggestion of logixologist. On the click event I added multiple if statements to check for the null value and then add build the query string. At the same time I made one of the dropdown to be a default value instead of "Select" and that would be my starting Where parameter. This works for me now. There might be a better way of writing the query, I am just beginner with asp.net

    Thanks for all your replies. I love this forum.