Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL LIKE Statement on a DateTime Type

How do you perform a LIKE statement on a column of DateTime datatype in SQL Server?

If I run the following SQL it returns me all the dates with 2009 in.

SELECT * FROM MyTable where CheckDate LIKE '%2009%'

However, if I want all the Oct, Nov & Dec dates I'd expect to be able to do the following:

SELECT * FROM MyTable where CheckDate LIKE '%2009-1%'

But this returns me nothing!

I'm giving the user a filter option where they type in the date string and as they type I filter the data. So if they type '20', I'd like to return all the dates with '20' within the date (so this could be all 2012 dates or a date value like 06/20/1999)

Can anybody help?

I'm using SQL Server 2008.

Thanks in advance.

like image 408
Sun Avatar asked Aug 16 '12 10:08

Sun


People also ask

Can we use like for datetime in SQL?

Like operator will not work with DateTime.

What is like %% in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Can you use like in an in statement SQL?

There is no combination of LIKE & IN in SQL, much less in TSQL (SQL Server) or PLSQL (Oracle). Part of the reason for that is because Full Text Search (FTS) is the recommended alternative.

What is the datatype for datetime in SQL?

The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in ' YYYY-MM-DD hh:mm:ss ' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59' . The TIMESTAMP data type is used for values that contain both date and time parts.


1 Answers

You can use something like this:

SELECT * 
FROM MyTable 
WHERE CheckDate >= '2009-10-01' AND CheckDate < '2010-01-01';
like image 139
LLAlive Avatar answered Oct 23 '22 04:10

LLAlive