by Matthew Noonan
20. March 2006 06:05
Can anyone explain this? I Googled around but didn't find any significant answers. The following code can be run against the Northwind database in SQL Server, where the CustomerID column is defined as nchar(5).
Apparently there is a bug when performing parameterized queries on columns using the LIKE clause, as in this example:
-- Returns no rows
SELECT * FROM [dbo].[Customers] WHERE [CustomerID] LIKE @CustomerID
However, this format works correctly:
-- Returns 39 rows
SELECT * FROM [dbo].[Customers] WHERE [CustomerID] LIKE '%A%'
As further proof of the bug, the NOT LIKE clause acts badly as well:
-- Returns all 92 rows
SELECT * FROM [dbo].[Customers] WHERE [CustomerID] NOT LIKE @CustomerID
-- Returns 53 rows
SELECT * FROM [dbo].[Customers] WHERE [CustomerID] NOT LIKE '%A%'
This was originally reported to me by Yu (Bruce) Houfang as an EasyObjects bug, but in reality it seems to be SQL Server's problem. However, I have checked in a work-around to the SqlDynamicQuery class so that if a nchar column is used in a LIKE clause, the direct string value is passed instead of the parameter.
Can anybody explain this behavior?