2011-09-15 64 views
0

我正在嘗試使用文本框中的搜索按鈕查詢Access數據庫,並將結果插入到列表框中。這裏是我到目前爲止的代碼:訪問數據庫的SQL搜索查詢?

Dim con As New OleDbConnection(DBcon) 
    Try 
     lbresults.Items.Clear() 
     Dim dr As OleDbDataReader 
     Dim command As New OleDbCommand("Select I.InstName, S.StuName FROM Instructor I, Student S WHERE I.InstName Like '%" & txtsearch.Text & "%' and S.StuName like '%" & txtsearch.Text & "%'", con) 

     con.Open() 

     command.Connection = con 
     dr = command.ExecuteReader 

     While dr.Read() 
      lbresults.Items.Add(dr("InstName")) 
      lbresults.Items.Add(dr("StuName")) 
     End While 

    Catch ex As Exception 

我遇到的問題是它的返回兩個InstName和StuName多次在列表框中。我猜這是因爲我正在做items.add兩次?我試圖使用「[oledbcommand變量名稱] .parameters.addwithvalue」,但我無法弄清楚如何用「like」函數來做到這一點。

回答

1

如果它加入InstName和StuName多次向下拉列表可能是因爲該查詢返回的記錄多次,因爲你正在做一個select ... where ... like...

試着改變你的SELECT語句(注意這個詞DISTINCT):

Dim command As New OleDbCommand("Select DISTINCT I.InstName, S.StuName FROM Instructor I, Student S WHERE I.InstName Like '%" & txtsearch.Text & "%' and S.StuName like '%" & txtsearch.Text & "%'", con) 
0

您的查詢是關聯兩個表而沒有指定關係。

有多種方法對皮膚一隻貓,但我想這樣做是爲了保證我控制的結果:

dim SQL as new string = _ 
    "Select 'Instructor' as NameType, I.InstName as NameValue " _ 
    "from Instructor I " _ 
    "where I.InstName Like '%" & txtsearch.Text & "%' " & _ 
    "union " & _ 
    "Select 'Student' as NameType, S.StuName as NameValue " _ 
    "from Student S " _ 
    "where S.StuName Like '%" & txtsearch.Text & "%' " 

Dim command As New OleDbCommand(SQL, con) 

整個數據集使用UNION與UNION ALL返回不重複的記錄與導師是當時表名稱重複的情況下。