In SQL Server I have a DATETIME column which includes a time element.
Example:
'14 AUG 2008 14:23:019'
What is the best method to only select the records for a particular day, ignoring the time part?
Example: (Not safe, as it does not match the time part and returns no rows)
DECLARE #p_date DATETIME
SET #p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime = #p_date
Note: Given this site is also about jotting down notes and techniques you pick up and then forget, I'm going to post my own answer to this question as DATETIME stuff in MSSQL is probably the topic I lookup most in SQLBOL.
Update Clarified example to be more specific.
Edit Sorry, But I've had to down-mod WRONG answers (answers that return wrong results).
#Jorrit: WHERE (date>'20080813' AND date<'20080815') will return the 13th and the 14th.
#wearejimbo: Close, but no cigar! badge awarded to you. You missed out records written at 14/08/2008 23:59:001 to 23:59:999 (i.e. Less than 1 second before midnight.)
Technique 1:
DECLARE #p_date DATETIME
SET #p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_datetime >= #p_date
AND column_datetime < DATEADD(d, 1, #p_date)
The advantage of this is that it will use any index on 'column_datetime' if it exists.
In SQL Server 2008, you could use the new DATE datatype
DECLARE #pDate DATE='2008-08-14'
SELECT colA, colB
FROM table1
WHERE convert(date, colDateTime) = #pDate
#Guy. I think you will find that this solution scales just fine. Have a look at the query execution plan of your original query.
And for mine:
Just compare the year, month and day values.
Declare #DateToSearch DateTime
Set #DateToSearch = '14 AUG 2008'
SELECT *
FROM table1
WHERE Year(column_datetime) = Year(#DateToSearch)
AND Month(column_datetime) = Month(#DateToSearch)
AND Day(column_datetime) = Day(#DateToSearch)
Something like this?
SELECT *
FROM table1
WHERE convert(varchar, column_datetime, 111) = '2008/08/14'
Technique 2:
DECLARE #p_date DATETIME
SET #p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE DATEDIFF( d, column_datetime, #p_date ) = 0
If the column_datetime field is not indexed, and is unlikely to be (or the index is unlikely to be used) then using DATEDIFF() is shorter.
Good point about the index in the answer you accepted.
Still, if you really search only on specific DATE or DATE ranges often, then the best solution I found is to add another persisted computed column to your table which would only contain the DATE, and add index on this column:
ALTER TABLE "table1"
ADD "column_date" AS CONVERT(DATE, "column_datetime") PERSISTED
Add index on that column:
CREATE NONCLUSTERED INDEX "table1_column_date_nu_nci"
ON "table1" ( "column_date" ASC )
GO
Then your search will be even faster:
DECLARE #p_date DATE
SET #p_date = CONVERT( DATE, '14 AUG 2008', 106 )
SELECT *
FROM table1
WHERE column_date = #p_date
I normally convert date-time to date and compare them, like these:
SELECT 'Same Date' WHERE CAST(getDate() as date) = cast('2/24/2012 2:23 PM' as date)
or
SELECT 'Same Date' WHERE DATEDIFF(dd, cast(getDate() as date), cast('2/24/2012 2:23 PM' as date)) = 0
This function Cast(Floor(Cast(GetDate() As Float)) As DateTime) returns a datetime datatype with the time portion removed and could be used as so.
Select
*
Table1
Where
Cast(Floor(Cast(Column_DateTime As Float)) As DateTime) = '14-AUG-2008'
or
DECLARE #p_date DATETIME
SET #p_date = Cast('14 AUG 2008' as DateTime)
SELECT *
FROM table1
WHERE Cast(Floor(Cast(column_datetime As Float)) As DateTime) = #p_date
How to get the DATE portion of a DATETIME field in MS SQL Server:
One of the quickest and neatest ways to do this is using
DATEADD(dd, DATEDIFF( dd, 0, #DAY ), 0)
It avoids the CPU busting "convert the date into a string without the time and then converting it back again" logic.
It also does not expose the internal implementation that the "time portion is expressed as a fraction" of the date.
Get the date of the first day of the month
DATEADD(dd, DATEDIFF( dd, -1, GetDate() - DAY(GetDate()) ), 0)
Get the date rfom 1 year ago
DATEADD(m,-12,DATEADD(dd, DATEDIFF( dd, -1, GetDate() - DAY(GetDate()) ), 0))
I know this isn't exactly how you want to do this, but it could be a start:
SELECT *
FROM (SELECT *, DATEPART(yy, column_dateTime) as Year,
DATEPART(mm, column_dateTime) as Month,
DATEPART(dd, column_dateTime) as Day
FROM table1)
WHERE Year = '2008'
AND Month = '8'
AND Day = '14'
SELECT *
FROM table1
WHERE CONVERT(varchar(10),columnDatetime,121) =
CONVERT(varchar(10),CONVERT('14 AUG 2008' ,smalldatetime),121)
This will convert the datatime and the string into varchars of the format "YYYY-MM-DD".
This is very ugly, but should work
Date can be compared in sqlserver using string comparision:
e.g.
DECLARE #strDate VARCHAR(15)
SET #strDate ='07-12-2010'
SELECT * FROM table
WHERE CONVERT(VARCHAR(15),dtInvoice, 112)>= CONVERT(VARCHAR(15),#strDate , 112)
DECLARE #Dat
SELECT *
FROM Jai
WHERE
CONVERT(VARCHAR(2),DATEPART("dd",Date)) +'/'+
CONVERT(VARCHAR(2),DATEPART("mm",Date)) +'/'+
CONVERT(VARCHAR(4), DATEPART("yy",Date)) = #Dat
The best way is to simply extract the date part using the SQL DATE() Function:
SELECT *
FROM table1
WHERE DATE(column_datetime) = #p_date;
SELECT * FROM tablename
WHERE CAST(FLOOR(CAST(column_datetime AS FLOAT))AS DATETIME) = '30 jan 2012'
SELECT CONVERT(VARCHAR(2),DATEPART("dd",doj)) +
'/' + CONVERT(VARCHAR(2),DATEPART("mm",doj)) +
'/' + CONVERT(VARCHAR(4),DATEPART("yy",doj)) FROM emp
There are many formats for date in SQL which are being specified. Refer https://msdn.microsoft.com/en-in/library/ms187928.aspx
Converting and comparing varchar column with selected dates.
Syntax:
SELECT * FROM tablename where CONVERT(datetime,columnname,103)
between '2016-03-01' and '2016-03-03'
In CONVERT(DATETIME,COLUMNNAME,103) "103" SPECIFIES THE DATE FORMAT as dd/mm/yyyy
In sqlserver
DECLARE #p_date DATE
SELECT *
FROM table1
WHERE column_dateTime=#p_date
In C#
Pass the short string of date value using ToShortDateString() function.
sample:
DateVariable.ToShortDateString();
Related
Working in SQL Server, I have a column that contains a year in numeric format. I need to make that year into a January 1st date of that 'year'. I've tried a few commands and the latest attempt is:
cast('01/01/' + X.[YEAR] as datetime)
What am I missing?
DECLARE #Year INT = 2010
SELECT CAST(CAST(#Year AS varchar) + '-1-1' AS DATETIME) -- 2010-01-01
Another way:
select GETDATE(),
DATEADD (day, - DATEPART(dayofyear, GETDATE()) + 1, CONVERT(date, GETDATE()))
I'm trying to create a report that gets records from a SQL Server database where the delivery date is today.
I've tried
select * from (tablename)
where delivery_date = getdate()
Although that didn't give me any errors, it didn't give me any records either.
I'm assuming it is because all dates are like:
2016-03-15 00:00:00.000
Perhaps, I need to truncate the date to remove the time-stamp and then try?
You can try a query like below
select * from (tablename)
where CAST(delivery_date as date) = CAST(getdate() as date)
Also if all delivery dates have time part like 00:00:00.000 for sure then
select * from (tablename)
where delivery_date = CAST(getdate() as date)
would work as good.
If delivery_date is always midnight (00:00:00.000), then compare it like this:
select * from (tablename)
where delivery_date = datediff(d, 0, getdate())
Using datediff like this is a quick way to truncate the time part of a datetime value.
I'd just create 2 params. One for StartTime and one for EndTime and use those in my query.
DECLARE #StartTime DATETIME,
#EndTime DATETIME
SET #StartTime = DATEDIFF(d,0,GETDATE())
SET #EndTime = DATEADD(d,1,#StartTime)
SELECT *
FROM [tablename]
WHERE delivery_date >= #StartTime
AND delivery_date < #EndTime
Try this:
DECLARE #Today DATETIME
SET #Today= CONVERT(date, getdate())
select * from (tablename)
where delivery_date = #Today
Yo need to remove the time part of the delivery_date field AND the GETDATE() value.
SELECT *
FROM (tablename)
WHERE DATEADD(dd, DATEDIFF(dd, 0, delivery_date), 0) = DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
I want to filter data from SQL Server 2008 R2 using FromDate and ToDate with another 2 user input dates. I want query for that.I want to filter data such a way that If user input 2 dates or any date in between of them lies in FromDate or 'ToDate' or in between date then it filters data.
For i.e.
FromDate ToDate
15-11-2014 20-11-2014
if user input dates are 11-11-2014 and 20-12-2014. It means in between dates of this 2 dates lies in between FromDate and ToDate so it should return this record.
Now, if user input dates are 11-11-2014 and 14-11-2014. It means in between dates of this 2 dates does not lie in between FromDate and ToDate so it should not return this record.
It must match given dates and as well as in between dates.
you Can use this :
Where
DATEADD(dd, 0, DATEDIFF(dd, 0, FromDate)) > '15-11-2014'
and
DATEADD(dd, 0, DATEDIFF(dd, 0, ToDate)) < '20-11-2014'
please check the example, you just compare the parameter with both datetime column to extract the rows.
declare #table table(id int,frdt datetime, todt datetime)
insert into #table values (1,GETDATE()-20, GETDATE()-19)
,(1,GETDATE()-9, GETDATE()-8)
,(1,GETDATE()+20, GETDATE()+18)
,(1,GETDATE(), GETDATE()-1)
,(1,GETDATE()-20, GETDATE())
,(1,GETDATE()-10, GETDATE()+10 )
select * from #table
declare #frdt datetime = null , #todt datetime = getdate()-10
select #frdt, #todt,* from #table
where
(#frdt is null or #frdt between frdt and todt)
and
(#todt is null or #todt between frdt and todt)
select #frdt = GETDATE() , #todt = GETDATE()
select #frdt, #todt,* from #table
where
(#frdt is null or #frdt between frdt and todt)
and
(#todt is null or #todt between frdt and todt)
From what I understand from your question.
select 'a' A, CONVERT(date,'11/15/2014') FromDate, CONVERT(date, '11/20/2014') ToDate into #Temp
declare #frmDate date;
declare #toDate date;
set #frmDate = Convert(date, '11/11/2014');
set #toDate = CONVERT(Date, '12/20/2014');
select * from #Temp where FromDate>=#frmDate and ToDate<=#toDate
set #frmDate = Convert(date, '11/11/2014');
set #toDate = CONVERT(Date, '11/14/2014');
select * from #Temp where FromDate>=#frmDate and ToDate<=#toDate
Hope fully it help you :)
I am trying to display records which have their date (I have a column Date in table) 30 days back from today's date. And once it gets displayed I need to make a new record by adding details with Date= today's date..
I tried this:
select * from
paymenthist
where
Date = CONVERT(datetime, CONVERT(varchar, DATEADD(day, -30, GETDATE()), 101))
But all records are getting displayed..
Ok, I admit the way I suggested may be inefficient, but if one is a datetime and the other is a date then I believe this will be more efficient than the >= <= approach because SQL is often not great at utilising indexes for queries like this, and under the covers a datetime is actually a floating point, so for pure efficiency, try this:
CREATE TABLE ##PaymentHistory
(
ID INT IDENTITY,
[Date] DATETIME,
Col1 INT,
Col2 INT
)
INSERT INTO ##PaymentHistory([Date],Col1,Col2)
VALUES(FLOOR(CAST(GETDATE() -29 AS FLOAT) ) ,1,1)
, (FLOOR(CAST(GETDATE() -30 AS FLOAT) ) ,2,2)
, (FLOOR(CAST(GETDATE() -31 AS FLOAT) ) ,3,3)
SET IDENTITY_INSERT ##PaymentHistory ON
INSERT INTO ##PaymentHistory(ID, [Date], Col1, Col2)
SELECT ID, GETDATE(), Col1, Col2
FROM ##PaymentHistory
WHERE CAST(Date AS FLOAT) = FLOOR(CAST(GETDATE() -30 AS FLOAT) )
SET IDENTITY_INSERT ##PaymentHistory OFF
It depends somewhat on the datatype of the date column, but try this.
select * from paymenthist where cast(Date as date) = cast(DATEADD(day, -30, GETDATE()) as date)
I would like to compare datetime datatype, like "20/12/2011 00:00:00", with compound string date format (I mean that it is composed of string of date, string of month and string of year).
For example, coloumn entime is datatime datatype which is stored "20/12/2011 00:00:00" data and other three column(date,month,year respectively) are string. so I want to compare between entime column with the date,month and year composed together, How I can write SQL Command to suppurt the above requirement ?
Hope you can help me ?
The best option is to convert the datetime to string and then make the needed comparisons.
You can see here how to make the conversion.
There is also the DATEPART function as an alternative.
SELECT *
FROM DateTable
WHERE
DATEPART(YEAR, [DATECOLUMN]) = #YearString
AND DATEPART(MONTH, [DATECOLUMN]) = #MonthString
AND DATEPART(DAY, [DATECOLUMN]) = #DayString
You can go below way, would you please try it out, thanks
SET DATEFORMAT DMY
SELECT CAST(CONVERT(VARCHAR(15), GETDATE(), 105) AS DATETIME)
SELECT CAST(('20'+'-'+'12'+'-'+'2011') AS DATETIME)
As an example:
SET DATEFORMAT DMY
SELECT CAST(CONVERT(VARCHAR(15), yourDateColumn, 105) AS DATETIME) FROM TableName
SELECT CAST((dayColumn+'-'+monthColumn+'-'+yearColumn) AS DATETIME)
FROM anotherTable
Finally the comparison:
SELECT t1.* FROM tableName t1, anotherTable t2
WHERE CAST(CONVERT(VARCHAR(15), t1.DateColumnName, 105) AS DATETIME)
= CAST((t2.dayColumn+'-'+t2.monthColumn+'-'+t2.yearColumn) AS DATETIME)
Is this your requirement ?
DECLARE #tblTemp TABLE
(
DAY VARCHAR(10)
,Month VARCHAR(10)
,Year VARCHAR(10)
)
DECLARE #dtDateTime VARCHAR(10) = '20/12/2011 00:00:00'
INSERT INTO #tblTemp VALUES
('01','01','2011'),
('01','02','2011'),
('01','03','2011'),
('01','04','2012');
select * from #tblTemp where CONVERT(DATE,Year +Month+DAY ,103) < CONVERT(DATE,#dtDateTime,103)