Ignoring the time element of a datetime field - sql-server

I have a datetime field in my table. I want to delete records based on a date but I am not interested in the time element. How would I write the SQL for this ? I am using MS SQL 2008.

For best use of indexes, I'd go for this kind of approach:
To delete all records for 1st December:
DECLARE #DateToDelete DATETIME
SET #DateToDelete = '20091201'
DELETE FROM MyTable
WHERE MyDateField >= #DateToDelete AND MyDateField < DATEADD(dd, 1, #DateToDelete)
The alternatives include:
DELETE FROM MyTable
WHERE CAST(CONVERT(VARCHAR(10), MyDateField, 120) AS DATETIME) = #DateToDelete
which converts each datetime value to just it's date part.
But I'd still go with my original way as it allows for more efficient execution.

If you use MS SQL 2008 then you could convert to a new DATE type
DELETE FROM table WHERE date_filed >= CONVERT(DATE,GETDATE())

Is the time relevant in any other place? If not, then you should use a DATE column instead. If you cannot, then the best way to seek a date part of a datetime in a WHERE clause is to use a range:
... WHERE dateColumn BETWEEN '20091221' and '20091222';
Note that given the datetime accuracy of 3ms a datetime like 20091221 23:59:59.999 may be aproximated to 20091222 00:00:00.000 and this can sometime create problems.
There is a great collection of blog posts on the topic of datetime at T-SQL Tuesday #001 (Date/Time Tricks): The Roundup

Try this:-
declare #date datetime
set #date = '2006-11-09'
select #date, dateadd(ms, -1, DATEADD(dd,1,#date))
delete from login
where datecreated between #date AND dateadd(ms, -1, DATEADD(dd,1,#date))

This is what datediff is for:
delete from Table where datediff(day,'2009-12-09',date_filled) = 0

Related

How can I compare a DATE value with the result of GETDATE()

I am trying to grant and revoke server roles for user id picked from a table.
I am using the following query to insert a row from master table to another table whenever the expiry date approaches, however the command is not inserting any rows into the slave table.
Insert into tbl2(userid, role, startdate, expirydate)
Select userid, role, startdate, expirydate
from tbl1
where expirydate = Dateadd(day,0, getdate())
If I use <= or >= the above query is working but that is not helpful when we have multiple rows in tbl1.
It's because GETDATE() returns a DATETIME value, and you're likely comparing it to a DATE, so you're effectively comparing values like this:
SELECT GETDATE() AS DateTimeValue,
CAST(GETDATE() AS DATE) DateValue;
Output:
DateTimeValue DateValue
2017-10-04 10:34:35.023 2017-10-04
By default, a DATE will have a time set to midnight if comparing to a DATETIME, like: 2017-10-04 00:00:00.000.
These values aren't going to be equal with a time included, so use CAST or CONVERT to get a DATE without the time:
where expirydate = Dateadd(day,0, CAST(GETDATE() AS DATE))
Although, it looks like you don't need that Dateadd on the WHERE clause, so remove it unless this is edited / sample code. So maybe edit it to this:
where expirydate = CAST(GETDATE() AS DATE)
Reference
GETDATE (Transact-SQL)
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.

In SQL Server how can I split a TransactionDateTime column into two separate columns Date and Time?

Team,
I have a TransactionDateTime column with data and time information together like this - 2016-03-14 03:32:44.000.
I am looking for a Split Function in SQL server 2005 that would split this column into two separate columns one for "Date" and another for "Time" and the final output will look like this.---- Date (2016-03-14) and Time (03:32:44.000)
TransactionDateTime Date Time
2016-03-1403:32:44.000 2016-03-14 03:32:44.000
Thanks.
Declare #dateTime datetime = getDate()
SELECT
#dateTime TransactionDateTime,
CONVERT(VARCHAR(10),#dateTime,101) as [Date],
CONVERT(VARCHAR(10),#dateTime,108) as [Time]
You can typecast to date/time accordingly since the output is varchar.
This should work...
select getdate(), convert(date, getdate()), convert(varchar(10),
getdate(), 108)
Replace "getdate()" with your TransactionDateTime.
Noel

Comparing dates with current date in Sql server

I have a table which has list of some events with dates. I am trying to write a stored procedure that will return only the upcoming events.
I have written the following query in the stored procedure:
SELECT *
FROM Events
WHERE tDate >= (select CAST(GETDATE() as DATE))
But this is not returning correct result. This is also showing results that have dates less than current date. How to write a query that will return all the events that have date equal or greater than today's date.
Edit: Dates that have been entered on the table have the format yyyy/dd/mm and getdate() returns date in the format yyyy/mm/dd. I think this is causing the problem. Dates that have been entered into the table has been taken using jquery date picker. Any solution to this problem?
Not sure why you have an additional select
SELECT *
FROM Events
WHERE tDate >= CAST(GETDATE() as DATE)
your DATE data is incorrectly stored within Sql Server. When your application passes the string '2015-09-04' and you save that your date column, it is saved as 4th Sept 2015 and not 9th April 2015. Hence your query returns such rows as they are greater than GETDATE().
Example
DECLARE #D VARCHAR(10) = '2015-09-04'
SELECT CONVERT(VARCHAR(20),CONVERT(DATE,#D),109)
you need to fix your data and then use a CONVERT with style when saving dates in your table from application, using something like this. CONVERT(DATE, '20150409',112)
DECLARE #D VARCHAR(10) = '20150409'
SELECT CONVERT(VARCHAR(20),CONVERT(DATE,#D,112),109)
Refer these threads for more info:
Impossible to store certain datetime formats in SQL Server
Cast and Convert

SQL: Query where date is like today

I have a little problem with my SQL Query:
I have this value on my table: 2014-10-23 00:00:00
I have a record like this each 2 minutes every day, and I need to SELECT all the value of today.
Now I made this:
WHERE mytable.data LIKE CURDATE()
and it doesn't work. I tried a lot of things found here on stackoverflow and nothing could help me.
Thanks for answer.
You don't say which version of SQL Server you are using, if you have the DATE data type available you can cast the datetime returned by getdate() or CURRENT_TIMESTAMP to strip off the time part.
But then you need a range to find all the matching rows, something like:
SELECT *
FROM mytable
WHERE mytable.data >= CAST(GETDATE() AS date)
AND mytable.data < CAST(DATEADD(day, 1, GETDATE()) AS date)
SQL Fiddle

Using Date datatype for removing time info from GetDate() is ok?

Typically I need to remove time info from GETDATE(). I need this because I have some DateTime fields where I know I am storing only date information so to make reliable comparisons (MyDate < GETDATE()) I need to remove time information from GETDATE()). Of course I could use the DATE datatype in MyDate, but this is ok for new applications, not for legacy ones.
I used to do it with CAST, but since in SQL Server 2008 there is also the DATE datatype it seems more readable.
Old approach
DECLARE #Today DateTime
SET #Today = (CAST(FLOOR(CAST( GETDATE() AS FLOAT)) AS DATETIME))
select #Today
New approach
DECLARE #TodayDate Date
Set #TodayDate = GETDATE()
select #TodayDate
May I go with the second or is there any caveat? (of coruse I use 2008 only!)
No caveats. Indeed it is the best way according to this answer.

Resources