[Withdrawing question: the issue arose from not escaping values submitted in web form. The ASP script removed unescaped spaces thereby causing the problem.]
In a web page I am attempting to conduct a search against a table in MS SQL Server using VBScript. The search uses a LIKE
clause (with wildcards). The search works fine if the input has no spaces in it. However, if there is a space in the input, the search returns nothing.
For example, if I search for IT Department
I get nothing, but if I search for Department
I get IT Department
. Somehow, the space between IT
and Department
is causing trouble. If I run the script directly against the server using SQL Server Management Studio, the search using IT Department
returns the proper results.
Also, if I don't use SQL placeholder parameters but instead put in search string directly, the search works.
It is only in the case where the search string contains a space and uses placeholders where the search fails.
Here is the code I am using:
Dim oCmd, OffDescParam, description, query
description = "IT Department"
Set oCmd = Server.CreateObject("ADODB.Command")
OffDescParam = "%" & description & "%"
Set objOffDescParam = _
oCmd.CreateParameter("@offdesc", adChar, adParamInput, Len(OffDescParam), OffDescParam)
query = "SELECT OfficialDescription " & _
"FROM [MyDatabase].[dbo].[Organizations] " & _
"WHERE (OfficialDescription LIKE ?)" & _
"ORDER BY OfficialDescription"
' If I use "WHERE (OfficialDescription LIKE '%IT Department%')" it works.
oCmd.ActiveConnection = "some/connection/string"
oCmd.ActiveConnection.CursorLocation = adUseClient
oCmd.CommandType = adCmdText
oCmd.CommandText = query
oCmd.Parameters.Append objOffDescParam
oCmd.Prepared = True
Set oRst = CopyRecordSet(oCmd.Execute)
oCmd.ActiveConnection.close