2012-01-03 50 views
0

嘿所有我需要的關於如何去這樣做的一些想法如下:增加超過1個ID搜索在SQL

我有一個用戶可以輸入一個ID來搜索文本框在數據庫中。它目前只是檢查1個ID。

實施例:

User types in ID 645378 

查詢看起來像:

SELECT * FROM blahTable WHERE theID = '645378'; 

現在,我期待,以允許用戶在一個時間鍵入超過1個ID並顯示這些結果。

所以又是一個例子是:

User types in ID(s): 645378, 78664, 901524 

而現在這是我的問題的用武之地。我如何根據用戶輸入到文本框中的ID數來創建查詢?

任何幫助將是偉大的!

David

回答

2

只需使用IN

SELECT * FROM blahTable WHERE theID IN (645378, 78664, 901524); 

請注意,如果你的價值觀是實際的字符串,而不是數字,那麼它將需要一些額外的工作:

Dim asValues As String() 
    Dim sbQuery As New System.Text.StringBuilder(5000) 

    ' Get the text, but remove any embedded semi-colons and single quotes for sql injection' 
    asValues = Miles.Text.Replace(";", " ").Replace("'", " ").Split(New Char() {","c}, StringSplitOptions.RemoveEmptyEntries) 

    sbQuery.Append("SELECT * FROM blahTable WHERE theID IN (") 

    Dim fUseComma As Boolean 

    ' Add each value to the query string. In this case, we are wrapping with ' 
    For Each sValue As String In asValues 
     ' Test the value for reasonableness (example only)' 
     If IsNumeric(sValue) Then 
      ' Only use the comma starting from the second valid item added 
      If fUseComma Then 
       sbQuery.Append(",") 
      Else 
       fUseComma = True 
      End If 
      sbQuery.Append("'").Append(CInt(sValue)).Append("'") 
     End If 
    Next 

    sbQuery.Append(")") 

    cmd.CommandText = sbQuery.ToString 
+0

我怎樣才能做到這一點,而不使用-1?我已經檢查過,以確保用戶首先在文本框中放入某些東西。 – StealthRT 2012-01-03 01:52:54

+0

@StealthRT:查看修訂後的答案 – 2012-01-03 01:56:44

+0

謝謝! :o)工作很棒! – StealthRT 2012-01-03 02:10:05

4

您可以在SQL中使用IN語句。

SELECT * FROM blahTable where theID in ('123','456','789') 

我會建議通過參數化查詢執行是爲了避免鮑比表(SQL注入)

+0

感謝您的評論,Origin! – StealthRT 2012-01-03 02:10:33

1

試試這個東西。

Dim xIDList As String = "645378, 78664, 901524" 'the user should separate ID by COMMA 
    Dim xID() As String = xIDList.Split(CChar(",")) 'splits the xIDlist 
    Dim xIDforQuery As String = String.Empty 
    For Each oID As String In xID 
     If oID.Trim.Length <> 0 Then 
      xIDforQuery &= "," & " '" & oID & "'"  ' if ID is not numeric 
      ' xIDforQuery &= "," & oID.ToString  ' use this line if ID is numeric 
     End If 
    Next 

    xIDforQuery = xIDforQuery.Trim 
    xIDforQuery = CStr(IIf(Mid(xIDforQuery, 1, 1) = ",", Mid(xIDforQuery, 2, xIDforQuery.Length - 1), xIDforQuery)) 

    Dim xFinalQuery As String = String.Empty 
    xFinalQuery = String.Format("SELECT * FROM blahTable where theID in ({0})", xIDforQuery) 

    ' xFinalQuery is the final query statement but this approach is vulberable to SQL Injection. 

Screenshot

+0

謝謝你的例子,約翰。 – StealthRT 2012-01-03 02:10:20

0

用戶如何知道他們想要的ID的?如果沒有太多的ID,使用多選列表框可以改進UI並簡化代碼。如果太多,則可以考慮使用自動完成的文本框供用戶選擇可從列表框中複製(移除)以供查詢使用的項目。