简体   繁体   中英

Query have different (no) result when using parameters

I have a strange problem. When I run the following query against my Sql Server 2014 database the result is as expected (note that LogDay is DATE not DATETIME ):

SELECT * FROM  myView WHERE LogDay BETWEEN '2018-09-06 01:01:59.000' AND '2018-09-06 01:31:59.000';

but when I use variables or parameters from ADO.NET, it returns no record :

DECLARE @startDate datetime,@toDate DATETIME
SET @startDate='2018-09-06 01:01:59.000';
SET @toDate='2018-09-06 01:31:59.000';

SELECT * FROM  myView WHERE LogDay BETWEEN @startDate AND @toDate;--returns no record

The following is generated query extracted from Sql Server profiler from ADO.NET ExecuterReader with the same parameters and values which again returns no record :

exec sp_executesql N'SELECT * FROM  myView WHERE LogDay BETWEEN @startDate AND @toDate;',N'@startDate datetime,@toDate datetime',@startDate='2018-09-06 01:01:00',@toDate='2018-09-06 01:31:00' --no record

This is a case created by implicit conversion based on data type precedence .

When using string literals, the values are converted to date which will effectively become 2018-09-06 and return all rows from that date without considering times.

When using parameters, the column is the one implicitly converted to datetime but with time in zeros. This will prevent any rows to be within the datetime range you sent.

In other words, datetime has higher precedence than date, and date has higher precedence than varchar (or other string types).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM