2011-06-10 59 views
0

我開發一個搜索系統中的SQL Server表的「標籤」的短語......檢查字符串使用經典ASP

用戶輸入以下搜索:「項目經理財政」

我們有一個表與標籤...

tbl_tags以下物品(短語)在表:

ID Tag 
1 Project Managers 
2 Programme Managers 
3 Finance 
4 Finance Managers 

我要拆分的搜索短語和拉那只有一個結果在數據庫中完全匹配。例如。 ID的1和3(不是2和4)

什麼是最好的方式去做這個SQL查詢?

我目前的方法非常冗長,涉及在查詢中爲每個單詞生成所有結果,例如,產生所有結果,然後使用instr(query,oRS("Tag"))比較每個產生的tag

我已啓用全文,所以如有必要可以使用contains

+0

你正在使用哪些DBMS? – 2011-06-10 08:43:21

+0

SQL企業管理器(DB是SQL Server 2008 R2) – 2011-06-10 08:46:28

回答

0

的副的書執行:

Option Explicit 

Const adVarChar = 200 ' remove if that constant is already defined 

Dim tags, term 
Dim placeholders, sql, cmd, result 

tags = Split(Request("searchterms"), " ") 

Set cmd = CreateObject("ADODB.Command") 
Set cmd.ActiveConnection = dbConnection ' I assume the connection object exists 

For Each term In tags  
    term = Trim(term) 
    If term <> "" Then 
    placeholders = placeholders & ",?"  
    cmd.Parameters.Append cmd.CreateParameter(, adVarChar, , 100, term) 
    End If 
Next 

If cmd.Parameters.Count > 0 Then 
    sql = "SELECT id FROM tbl_tags WHERE tag IN (" & Mid(placeholders, 2) & ")" 
    cmd.CommandText = sql 

    Set result = cmd.execute 

    While Not result.EOF 
    Response.Write result.Fields("id") ' whatever 
    result.MoveNext 
    Wend 
End If 

也可以看看到documentation of CreateParameter