如何在两个表中搜索?

时间:2015-01-21 09:25:53

标签: sql-server vb.net

我只想在一个textbox中进行搜索,如果搜索到的id在学生或教师表中相同,它将会查看表单并显示数据,但我不会这样做。我知道怎么做。

   cn.Open()

    With cmd
        .Connection = cn
        If (dt.Rows.Count > 0) Then
            .CommandText = "SELECT * FROM Students WHERE Familyname = '" & search.Text & "' OR Firstname = '" & search.Text & "' OR StudentID = '" & search.Text & "' OR RFID = '" & search.Text & "'"
            Searchfrm.Show()
            da.SelectCommand = cmd
            dt.Clear()
            da.Fill(dt)
            cn.Close()

        Else : .CommandText = "SELECT * FROM FactandStaff WHERE Familyname LIKE '%" & search.Text & "%' OR Firstname LIKE '%" & search.Text & "%' OR FacultyorStaffID LIKE '%" & search.Text & "%' OR RFID LIKE '%" & search.Text & "%' OR College LIKE '%" & search.Text & "%'"
            searchfrm2.Show()
            da.SelectCommand = cmd
            dt.Clear()
            da.Fill(dt)
            cn.Close()
        End If
    End With

1 个答案:

答案 0 :(得分:0)

我假设您需要显示两个表格中的常规数据,例如,您要显示FirstNameFamilyName,然后您只需要运行1个查询,如下所示

"Select 1 as [type] , FirstName, LastName from Students "+
" WHERE Familyname = '" & search.Text & "' OR Firstname = '" & search.Text & "' OR StudentID = '" & search.Text & "' OR RFID = '" & search.Text & "'"+
+" Union All "
+" Select 2 , FirstName, LastName from FactandStaff )"+
+"WHERE Familyname LIKE '%" & search.Text & "%' OR Firstname LIKE '%" & search.Text & "%' OR FacultyorStaffID LIKE '%" & search.Text & "%' OR RFID LIKE '%" & search.Text & "%' OR College LIKE '%" & search.Text & "%'"

p.s:而不是像这样写,请使用string.format,如下所示

String.Format("Select 1 as [type], FirstName, LastName from Students where Familyname = '{0}' or Firstname = '{0}' OR StudentID = {0} OR RFID = '{0}' \r Union All \r Select 2,FirstName, LastName from FactandStaff WHERE Familyname LIKE '%{0}%' OR Firstname LIKE '%{0}%' OR FacultyorStaffID LIKE '%{0}%' OR RFID LIKE '%{0}%' OR College LIKE '%{0}%'", search.Text);