使用者輸入「中國人民」,系統自動拆解為「中國」、「人民」等雙字組合,並以 OR 條件查詢,模擬 3721 風格智慧搜尋。
建立 db_sample.mdb,資料表 T_Sample:
ID (Autonumber)U_Name (Text)U_Info (Memo)<form name="frm_Search" method="get" action="Search.asp">
請輸入關鍵字:<input type="text" name="key" size="10">
<input type="submit" value="搜尋">
</form>
<%
Dim strProvider, CNN
strProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("data/db_Sample.mdb")
Set CNN = Server.CreateObject("ADODB.Connection")
CNN.Open strProvider
%>
<%
Function AutoKey(strKey)
Const lngSubKey = 2 ' 子字串長度
Dim lngLenKey, strNew1, strNew2, i, strSubKey
' 防注入:過濾危險字元
If InStr(strKey, "=") Or InStr(strKey, "`") Or InStr(strKey, "'") Or InStr(strKey, " ") Or _
InStr(strKey, Chr(34)) Or InStr(strKey, ",") Or InStr(strKey, "<") Or InStr(strKey, ">") Then
Response.Redirect "error.htm"
End If
lngLenKey = Len(strKey)
Select Case lngLenKey
Case 0: Response.Redirect "error.htm"
Case 1: strNew1 = "" : strNew2 = ""
Case Else
For i = 1 To lngLenKey - (lngSubKey - 1)
strSubKey = Mid(strKey, i, lngSubKey)
strNew1 = strNew1 & " OR U_Name LIKE '%" & strSubKey & "%'"
strNew2 = strNew2 & " OR U_Info LIKE '%" & strSubKey & "%'"
Next
End Select
' 組合完整 SQL:原關鍵字 + 所有雙字組合
AutoKey = "SELECT * FROM T_Sample WHERE U_Name LIKE '%" & strKey & "%' OR U_Info LIKE '%" & strKey & "%'" & strNew1 & strNew2
End Function
%>
<%
Dim S_Key, SQL, RST
S_Key = Request("key")
If S_Key = "" Then
Response.Write "<font color=red>請輸入關鍵字</font>"
Else
SQL = AutoKey(S_Key)
Set RST = CNN.Execute(SQL)
If RST.EOF And RST.BOF Then
Response.Write "<font color=red>未找到任何結果!</font>"
Else
Response.Write "搜尋關鍵字:" & S_Key & ",共找到 " & RST.RecordCount & " 筆:<p>"
While Not RST.EOF
Response.Write "<font size=2><a href='info.asp?ID=" & RST("ID") & "' target='_blank'>" & RST("U_Name") & "</a></font>"
Response.Write "<font size=1>" & Left(RST("U_Info"), 150) & "</font><p>"
RST.MoveNext
Wend
RST.Close
End If
Set RST = Nothing
End If
CNN.Close : Set CNN = Nothing
%>