简体   繁体   中英

datetime query in SQL

I have to write a query to get rows where date is like current date. I don't want to compare the the time part but only date part. Like today's date is 2014-05-03 but in table its in datetime as 2014-05-03 10:08:22

i tried [ http://www.w3schools.com/sql/func_convert.asp]

but could not do anything..

my query is like

select *from dbo.param where cvdatetime like '2014-05-03%';

but its does not work although if i use

select *from dbo.param where cvdatetime like '%2014%';

it works so i don't get why "like" can't work in the previous case

i just want to compare the date part only not the time part..

like in c# i will take the current date as

 string today_n = DateTime.Now.ToShortDateString();

which will give only today's date the query will be like

string query="select *from dbo.param where cvdatetime like '" + today_n + "%'"

what is the correct way? also i want that whatever be the system date format query should work like even if system date time format is dd-mm-yyyy hh:mm:ss tt the query should work how can i ensure this?

Adding new requirement what if I need to check date hh:mm: only not seconds

ie, 2014-05-04 12:00: part only not seconds part

You cannot use like as such on datetime column.

Use the below:

select * from dbo.param where convert(varchar, cvdatetime, 120) like '%2014%';

As, far your second question is concerned, you'll have to use parameterized queries to avoid sql injection attacks.

Using SQL Server 2005 or later, just convert the datetime to date :

select *
from dbo.param
where cast(cvdatetime as date) = '2014-05-03';

Do not think about dates as strings. Think of them as dates, with the string format only used for output purposes. Or, if you have to make an analogy to another type, think numbers. As an example, go into Excel, put a date into a cell. Nicely format it. Then set another cell equal to the value of the first cell ( =A1 for example). Format that as a number and you will see some strange number, probably in the range of about 40,000. Excel stores dates as number of days since 1970-01-01. SQL has a similar (but different) storage mechanism.

You can use the following for the current date:

SELECT *
FROM dbo.param
WHERE CONVERT(DATE, cvdatetime)  = CONVERT(DATE, GETDATE())

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