Bad T-SQL, bad: how a date-specific query kept me up half the night
I learned something new today about doing date-specific queries in T-SQL. Let me first preface this with the fact that I've never done a date-specific query for a single date, having only ever done so for ranges where a SELECT * FROM TableName WHERE DateField >= '7/15/2004' was ever used.
Apparently, this doesn't hold true for getting the precise date (at least when working with date fields in SQL Server 2000 of type SMALLDATETIME). I tried and tried to get the following to work, without any luck:
SELECT * FROM TableName WHERE DateField = '7/15/2004'
Here's what I found does work, both returning the same resultset:
DECLARE @QueryDate SMALLDATETIME
SET @QueryDate = '7/7/2004'
SELECT * FROM TableName WHERE [Date] BETWEEN @QueryDate AND DATEADD(day,1,@QueryDate);
SELECT * FROM TableName WHERE [Date] BETWEEN @QueryDate + ' 00:00:00' AND @QueryDate + ' 23:59:59';
Weird. I knew I should have been an encyclopedia salesman.