简体   繁体   中英

How to filter Time portion of a DateTime column

I want to retrive data from table according to a particular time so I use this query below.

    select * from a
    where convert(smalldatetime,date,datepart(hh,date)) ='09:12:00'

but I get no row as result. So what should I do for my expected result?

You can convert directly to varchar as below

SELECT * FROM a
WHERE CONVERT(VARCHAR(8), [date], 108) = '09:12:00'

Try this:

SELECT *
FROM a
WHERE CONVERT(VARCHAR(8), [DATE],108) = '09:12:00'

Your datatype is already smalldatetime so you have to convert to varchar and compare with string.

EDIT:

Answer explanation:

You have smalldatetime inside [DATE] column. For example 2015-10-01 09:12:00 . To compare only time you need to convert to string which contains only time. For this reason you will use command CONVERT from TSQL.

It will convert smalldatetime to 8 characters string. As a result you will have 09:12:00 and then you compare it with your string.

//CONVERT(data_type(length),expression,style)

SELECT * FROM a
WHERE CONVERT(varchar(8),[columnName],108) = '09:12:00'

In Sql server 2008 you can convert to TIME. By specifying TIME(0) you have the desired format:

SELECT * 
FROM a
WHERE CAST(date as time(0)) ='09:12:00'

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