checking for smalldatetime column equal to GetDate() - ignoring time - sql

I have a column of smalldatetime type, date
I'd like to run a query that only retrieves rows:
where date = convert(smalldatetime,GetDate())
However, this is never finding matches as it is also comparing the times.
Ie: 01-01-2010 12:23:00 != 01-01-2010 12:25:00
How can I find matches on only the date portion?

One way which will utilize the index
where date >= dateadd(dd, datediff(dd, 0, getdate()), 0)
and date < dateadd(dd, datediff(dd, 0, getdate()), +1)
See also: How Does Between Work With Dates In SQL Server?

Try:
where datediff(dd, yourdate, GetDate()) = 0

Convert your DateTime values to Date values. That will store only the date portion for you to compare.
A list of available Date and Time datatypes in MSSQL is here.

You could try:
Where CAST(FLOOR(CAST([Date] AS FLOAT)) AS DATETIME) = CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)
This would make both dates appear as:
2010-08-05 00:00:00.000
and thus only comparing the dates ignoring the times

found this:
CAST(CONVERT (CHAR(8), GETDATE(), 112) AS smalldatetime)
from here:
reference
this sql worked for me when I added a smalldatetime field to an existing table:
SELECT testing
FROM LTCCAssessment
WHERE (testing = CAST(CONVERT(CHAR(8), GETDATE(), 112) AS smalldatetime))

where cast(CONVERT(char(10),DATETIME_FIELD_1,101) as datetime)
= cast(CONVERT(char(10),DATETIME_FIELD_2,101) as datetime)

Related

How to get only date part while using dateadd() and getdate()

I want to display records of last 4 months from current date.
I don't want to consider time
How can I get just date part from the below query?
where OrderDate >= DATEADD(month, -4, GETDATE())
If you're using SQL Server 2008, try converting GETDATE() to a DATE directly.
WHERE OrderDate >= DATEADD(month, -4, CONVERT(date, GETDATE()))
http://sqlfiddle.com/#!3/df444/2
Why not use the simple DATEDIFF function
where DATEDIFF(MM, OrderDate, GETDATE()) < 4
If you can't use the DATE type, there's the old way: convert the DATETIME value to CHAR, trim the hour components and then convert it back to DATETIME, so the hour components will be zeroed:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112), 112)
-- -----------------------
-- 2014-02-25 00:00:00.000
The important thing is to use the function over the scalar parameter (and not on the column) to allow the usage of existing indexes.

How to get 00:00:00 in datetime, for First of Month?

I wrote a query to obtain First of month,
SELECT DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as First_Of_Month;
for which i do get the appropriate output, but my time stamp shows the current time.
Here's what I am doing in the query, hope i make sense.
using datepart i calculated the no. of days (int) between the 1st and today (27-1 =26)
Then using dateadd function, i added "-datepart" to get the first of the month.
This is just changing the date, what should i look at or read about in order to change the time. I am assuming that it would have something to do with 19000101
For SQL Server 2012 (thanks adrift and i-one)
DECLARE #now DATETIME = CURRENT_TIMESTAMP;
SELECT DATEADD(DAY, 1, EOMONTH(#now, -1));
-- or
SELECT DATEFROMPARTS(YEAR(#now), MONTH(#now), 1);
For SQL Server 2008+
DECLARE #now DATETIME = CURRENT_TIMESTAMP;
-- This shorthand works:
SELECT CONVERT(DATE, #now+1-DAY(#now));
-- But I prefer to be more explicit, instead of relying on
-- shorthand date math (which doesn't work in all scenarios):
SELECT CONVERT(DATE, DATEADD(DAY, 1-DAY(#now), #now));
For SQL Server 2005
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0);
A caveat if you're using this SQL Server 2005 method: you need to be careful about using expressions involving DATEDIFF in queries. SQL Server can transpose the arguments and lead to horrible estimates - as seen here. It might actually be safer to take the slightly less efficient string approach:
SELECT CONVERT(DATETIME, CONVERT(CHAR(6), GETDATE(), 112) + '01');
SELECT convert(varchar(10),DATEADD(DAY, - (DATEPART(DAY,GETDATE())-1), GETDATE()),120)+' 00:00:00' as First_Of_Month;
Just the date
DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)
So for a month it is:
DATEADD(mm, DATEDIFF(mm, 0, GETDATE()), 0) AS FirstDatetimeOfMonthmm,
I think the easiest way is to cast the result to date:
SELECT cast(DATEADD(DAY, -(DATEPART(DAY,GETDATE())-1), GETDATE()) as date) as First_Of_Month
One alternative:
SELECT cast(
cast(datepart(yyyy, getdate()) as varchar)
+ '-'
+ cast(datepart(mm, getdate()) as varchar) + '-01 00:00:00'
as datetime)
Build up the date from year/month components, then tack on the 1st and midnight.
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) as First_Of_Month;
Try following code:
SELECT CAST(CAST(GETDATE() AS DATE) AS DATETIME) AS StartDateTime,
DATEADD(ms, -3, CAST(CONVERT(date, DATEADD (DAY,1,GETDATE())) AS varchar(10))) AS EndDateTime
Result:
StartDateTime
EndDateTime
2022-05-23 00:00:00.000
2022-05-23 23:59:59.997

Getting rows between date range is not working in SQL Server

In SQL Server 2008R2 fetching data between two dates is not working.
I am using the following code to get rows from the INVOICE table where the CREATED_DATE is between #startdate and #enddate, which are the parameters I am sending to the stored procedure.
Select *
from INVOICES INV
where CONVERT(Varchar(10), INV.CREATED_DATE, 105)
BETWEEN CONVERT(VARCHAR(10), #startdate, 105)
AND CONVERT(VARCHAR(10), #enddate, 105)
It is not working properly, driving me nuts..
What I am doing wrong?..
select * from
invoices inv
where inv.created_date >= dateadd(dd, 0, datediff(dd, 0, #startdate))
and inv.created_date < dateadd(dd, 1, datediff(dd, 0, #enddate))
First of all, do not convert your start/end and column's dates to varchar, and if you do so remember that 105 (returns dd-mm-yyyy) is not comparable, 112 (returns yyyymmdd) would be better (when you are interested in date part only). But what I've said it's better not to convert and just compare dates.
Added:
And little explanation: dateadd(dd, 0, datediff(dd, 0, #startdate)) - returns date part only of datetime, dateadd(dd, 1, datediff(dd, 0, #startdate)) - returns next day date part only.
Query returns all rows for your parameters inclusively (regardless of the hour).
Since you're on SQL Server 2008 R2, you could just convert everything to the DATE format:
SELECT *
FROM dbo.INVOICES INV
WHERE CAST(INV.CREATED_DATE AS DATE)
BETWEEN CAST(#startdate AS DATE) AND CAST(#enddate AS DATE)
Since you're using the DATE type, you're independent of any dateformat or language settings or any of those tricky features. SQL Server will just compare dates - as it should.
And of course: if you make your stored procedure parameters #startdate and #enddate to be of type DATE from the beginning, then you can save yourself those two CAST operations, too!
SELECT *
FROM dbo.INVOICES INV
WHERE CAST(INV.CREATED_DATE AS DATE) BETWEEN #startdate AND #enddate
(and if you made CREATED_DATE of type DATE - you could even forget about that last CAST in the statement, too!)
Default setting is yyyy-MM-dd
If you use 105 which means you're trying to parse date as format dmy, so before executing add below line at the top of your query.
SET DATEFORMAT DMY

TSQL SELECT previous date's records

I want to select all records from a table Log where the DateAndTime field values (of type datetime) are for the day before today, whatever day it is.
So if today is 2011-06-08, I want to select all rows where DateAndTime is greater than or equal to 2011-06-07 00:00:00 and also less than 2011-06-08 00:00:00.
I'm guessing the potential pitfall here would be it's behaviour on the 1st day of the month, as obviously a date like 2011-06-00 is invalid, and should be 2011-05-31.
For SQL Server 2008 you can use this.
select *
from [log]
where cast(DateAndTime as date) = cast(getdate()-1 as date)
Pre 2008 you can use this
select *
from [log]
where DateAndTime >= dateadd(d, datediff(d, 0, getdate())-1, 0) and
DateAndTime < dateadd(d, datediff(d, 0, getdate()), 0)
Related on DBA: Cast to date is sargable but is it a good idea?
SELECT * FROM Log
WHERE DateAndTime >= DATEADD(DAY,-1, CAST(GETDATE() AS DATE))
AND DateAndTime < CAST(CAST(GETDATE() AS DATE) AS DATETIME)
This example assumes SQL Server:
select *
from log
where convert(varchar(8), DateAndTime , 112) = convert(varchar(8), getdate()-1, 112)
Essentially, convert the date to yyyymmdd (the 112 parameter) and then check it is equal to yesterday's date (getdate()-1), also converted to yyyymmdd.
Assuming SQL Server
declare #today date
set #today = GETDATE()
select * from Log where DateAndTime between DATEADD(dd, -1, #today ) and #today
It should include conditional operator and not between .
Otherwise it includes today's records as well.
Declare #today date
Set #today = GETDATE()
Select YourcolumnNames from log
Where DateAndTime >= DATEADD(dd, -1, #today ) and DateAndTime < DATEADD(dd, -1, #today )
Moreover, you should mention the column name and * should be avoided in the select statement. This can improve the performance

How to select date without time in SQL

When I select date in SQL it is returned as 2011-02-25 21:17:33.933. But I need only the Date part, that is 2011-02-25. How can I do this?
For SQL Server 2008:
Convert(date, getdate())
Please refer to https://learn.microsoft.com/en-us/sql/t-sql/functions/getdate-transact-sql
I guess he wants a string.
select convert(varchar(10), '2011-02-25 21:17:33.933', 120)
120 here tells the convert function that we pass the input date in the following format: yyyy-mm-dd hh:mi:ss.
Using CAST(GETDATE() As Date) worked for me
The fastest is datediff, e.g.
select dateadd(d, datediff(d,0, [datecolumn]), 0), other..
from tbl
But if you only need to use the value, then you can skip the dateadd, e.g.
select ...
WHERE somedate <= datediff(d, 0, getdate())
where the expression datediff(d, 0, getdate()) is sufficient to return today's date without time portion.
CAST(
FLOOR(
CAST( GETDATE() AS FLOAT )
)
AS DATETIME
)
http://www.bennadel.com/blog/122-Getting-Only-the-Date-Part-of-a-Date-Time-Stamp-in-SQL-Server.htm
For 2008 older version :
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
you can use like this
SELECT Convert(varchar(10), GETDATE(),120)
In case if you need the time to be zeros like 2018-01-17 00:00:00.000:
SELECT CONVERT(DATETIME, CONVERT(DATE, GETDATE()), 121)
I would use DATEFROMPARTS function. It is quite easy and you don't need casting. As an example this query :
Select DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), DAY(GETDATE())) as myNewDate
will return
2021-01-21
The good part you can also create you own date, for example you want first day of a month as a date, than you can just use like below:
Select DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) as myNewDate
The result will be:
2021-01-01
You can try this one too.
SELECT CONVERT(DATE, GETDATE(), 120)
Its too late but following worked for me well
declare #vCurrentDate date=getutcdate()
select #vCurrentDate
When data type is date, hours would be truncated
It's a bit late, but use the ODBC "curdate" function (angle brackes 'fn' is the ODBC function escape sequence).
SELECT {fn curdate()}
Output: 2013-02-01
Convert it back to datetime after converting to date in order to keep same datatime if needed
select Convert(datetime, Convert(date, getdate()) )
If you want to return a date type as just a date use
CONVERT(date, SYSDATETIME())
or
SELECT CONVERT(date,SYSDATETIME())
or
DECLARE #DateOnly Datetime
SET #DateOnly=CONVERT(date,SYSDATETIME())
Use is simple:
convert(date, Btch_Time)
Example below:
Table:
Efft_d Loan_I Loan_Purp_Type_C Orig_LTV Curr_LTV Schd_LTV Un_drwn_Bal_a Btch_Time Strm_I Btch_Ins_I
2014-05-31 200312500 HL03 NULL 1.0000 1.0000 1.0000 2014-06-17 11:10:57.330 1005 24851e0a-53983699-14b4-69109
Select * from helios.dbo.CBA_SRD_Loan where Loan_I in ('200312500') and convert(date, Btch_Time) = '2014-06-17'
select DATE(field) from table;
field value: 2020-12-15 12:19:00
select value: 2020-12-15
In PLSQL you can use
to_char(SYSDATE,'dd/mm/yyyy')
First Convert the date to float (which displays the numeric), then ROUND the numeric to 0 decimal points, then convert that to datetime.
convert(datetime,round(convert(float,orderdate,101),0) ,101)
Try this.
SELECT DATEADD(DD, 0, DATEDIFF(DD, 0, GETDATE()))
I would create a scalar function and use format () to set the datatype you want to see. It is must easy on the maintenance later.
Personal favorite:
select convert(datetime, convert(int, getdate()))