in MySQL
select * from record where register_date like \'2009-10-10%\'
What is the syntax in SQL Server?
Unfortunately, It is not possible to compare datetime towards varchar using 'LIKE' But the desired output is possible in another way.
select * from record where datediff(dd,[record].[register_date],'2009-10-10')=0
The LIKE
operator does not work with date parts like month or date but the DATEPART
operator does.
Command to find out all accounts whose Open Date was on the 1st:
SELECT *
FROM Account
WHERE DATEPART(DAY, CAST(OpenDt AS DATE)) = 1`
*CASTING OpenDt
because it's value is in DATETIME
and not just DATE
.
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.
Try this
SELECT top 10 * from record WHERE IsActive = 1 and CONVERT(VARCHAR, register_date, 120) LIKE '2020-01%'
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.
Consult the MSDN DATEPART docs for the full list of valid arguments.
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'