这个答案首先试图解释为什么EpisodeDate like '%2013-01-22%'
解决方案不起作用,你可以做些什么来获得所需的结果like ...
(我不推荐),最后,我提出了两个解决方案(有和没有隐式转换)。所有查询都可以在AdventureWorks2008R2 示例数据库上执行:
/*
CREATE INDEX IX_SalesOrderHeader_OrderDate
ON Sales.SalesOrderHeader(OrderDate)
*/
-- It CONVERTs datetime values to VARCHAR with style 0 {Style 0 = mon dd yyyy hh:miAM (or PM)}
-- http://technet.microsoft.com/en-us/library/ms187928.aspx
SELECT TOP(1500)
h.OrderDate,h.SalesOrderID,
CONVERT(VARCHAR(40),h.OrderDate,0) AS OrderDateAsVarChar40, -- Explicit conversion from DATETIME to VARCHAR(40) with style 0
LEFT(h.OrderDate,40) AS ForcingImplicitConvertOnDateTimeColumn -- Implicit conversion because the first argument of LEFT function must be a %CHAR
FROM Sales.SalesOrderHeader h;
/*
OrderDate SalesOrderID OrderDateAsVarChar40 ForcingImplicitConvertOnDateTimeColumn
----------------------- ------------ -------------------- --------------------------------------
2005-07-01 00:00:00.000 43659 Jul 1 2005 12:00AM Jul 1 2005 12:00AM
...
2005-11-19 00:00:00.000 44685 Nov 19 2005 12:00AM Nov 19 2005 12:00AM
2005-11-20 00:00:00.000 44686 Nov 20 2005 12:00AM Nov 20 2005 12:00AM
...
2008-07-31 00:00:00.000 75123 Jul 31 2008 12:00AM Jul 31 2008 12:00AM
*/
-- Result: No rows
SELECT h.OrderDate,h.SalesOrderID
FROM Sales.SalesOrderHeader h
-- The syntax of LIKE operator shows that h.OrderDate must be %CHAR
-- so, SQL Server add an implicit conversion of OrderDate values from DATETIME to VARCHAR
-- http://technet.microsoft.com/en-us/library/ms179859.aspx
WHERE h.OrderDate LIKE '%2005-11-20%'
执行计划:
-- Result: 5 rows
-- I get 5 rows but it's the execution plan is unoptimized (because of Index Scan; see first execution plan)
SELECT h.OrderDate,h.SalesOrderID
FROM Sales.SalesOrderHeader h
WHERE h.OrderDate LIKE 'Nov 20 2005%';
-- Result: 5 rows
-- I get 5 rows and the execution plan includes
-- (1) Index Seek operator instead of Index Scan
-- (2) and implicit conversion of @1 and @2 parameters from varchar to datetime
SELECT h.OrderDate,h.SalesOrderID
FROM Sales.SalesOrderHeader h
WHERE h.OrderDate >= '20051120' AND h.OrderDate < '20051121';
执行计划:
-- Result: 5 rows
-- I get 5 rows and the execution plan includes
-- (1) Index Seek operator instead of Index Scan
-- (2) and no implicit conversion of @1 and @2 parameters
-- See Date, Time, and Timestamp Literals: http://msdn.microsoft.com/en-us/library/windows/desktop/ms710282(v=vs.85).aspx
SELECT h.OrderDate,h.SalesOrderID
FROM Sales.SalesOrderHeader h
WHERE h.OrderDate >= {d '2005-11-20'} AND h.OrderDate < {d '2005-11-21'};
执行计划: