views:

836

answers:

5

in MySQL

select * from record where register_date like '2009-10-10%'

What is the syntax in SQL Server?

Thank you.

+2  A: 

There's no direct support for LIKE operator against DATETIME variables, but you can always cast the DATETIME to a VARCHAR:

SELECT (list of fields) FROM YourTable
WHERE CONVERT(VARCHAR(25), register_date, 126) LIKE '2009-10-10%'

Check the MSDN docs for a complete list of available "styles" in the CONVERT function.

Marc

marc_s
That seems to me the *least* desirable way to handle datetimes...
Marc Gravell
agreed - but the OP requested a way to handle datetime with LIKE.... But I agree - datetimes should preferably be handled with ranges like >= and <= or BETWEEN - much better approach
marc_s
Thank you everyone. Sorry I'm just a newbie for SQL.
+2  A: 

If you do that, you are forcing it to do a string conversion. It would be better to build a start/end date range, and use:

declare @start datetime, @end datetime
select @start = '2009-10-10', @end = '2009-11-10'
select * from record where register_date >= @start
           and register_date < @end

This will allow it to use the index (if there is one on register_date), rather than a table scan.

Marc Gravell
Thank you. Sorry I'm just a newbie for SQL.
+1  A: 

You can use CONVERT to get the date in text form. If you convert it to a varchar(10), you can use = instead of like:

select *
from record
where CONVERT(VARCHAR(10),register_date,120) = '2009-10-10'

Or you can use an upper and lower boundary date, with the added advantage that it could make use of an index:

select *
from record
where '2009-10-10' <= register_date
and register_date < '2009-10-11'
Andomar
Thank you very much.
A: 

You could use the DATEPART() function

select * from record 
where (DATEPART(yy, register_date) = 2009
AND DATEPART(mm, register_date) = 10
AND DATEPART(dd, register_date) = 10)

I find this way easy to read, as it ignores the time component, and you don't have to use the next day's date to restrict your selection. You can go to greater or lesser granularity by adding extra clauses, using the appropriate DatePart code, e.g.

AND DATEPART(hh, register_date) = 12)

to get records made between 12 and 1.

Rafe Lavelle
If there's an index on register_date, this will completely ignore the index and performance will suffer. Probably quite badly.
Chris J
Ok, but it does avoid the problem of using the string equivalent of the day after the date in question, which is being suggested in a few of the answers here. Tricky where the date in question is the end of the month, or year.
Rafe Lavelle
+1 Why was this downvoted?
Andomar
Thank you. Sorry I'm just a newbie for SQL.
A: 

For a healthy discussion on this (including why it's bad to treat DATETIME values like strings, and why it can be bad to use "BETWEEN" or ">= AND <="), see: http://is.gd/4EgDF

Aaron Bertrand