Date filter on column in sql - sql-server

I have query that filtered by date, for now it take only the last 24h from the moment I execute it, for doing that I'm using the next code:
( DateDiff(HH, vw_public_task.complete_date, getdate()) < 25)
There is a way that my date filter will give query results for the last 24h but not depending on my current hour but according to "day 08:00am" -- "day+1 08:00am" at any time that I execute it?.
For example if I execute my query now I want to see date results from yesterday 08:00am till today 08:00am.

You can calculate yesterday 8am using the formula:
-- Yesterday at 8 am.
SELECT
DATEADD(HOUR, 8, CAST(CAST(DATEADD(DAY, -1, GETDATE()) AS DATE) AS DATETIME)) AS Yesterday8AM
;
GetDate returns the current date. The innermost date add subtracts one day. Casting this as a date removes the timestamp. Casting this back to a DateTime gives yesterday at midnight. Now we are dealing with a DateTime we can use date add, again, to add 8 hours.
If you are using SQL Server 2012, or above, consider the native function DATETIME2FROMPARTS instead.

Use Date() (How to part DATE and TIME from DATETIME in MySQL).
( DateDiff(HH, vw_public_task.complete_date, Date(getdate())+8 ) < 25)

Related

dynamically changing dates in a temp table

So i have a very specific task. I run some sql statements within which there is a temp table which contains date ranges specific to countries.
e.g.
INSERT INTO #dateRange(durationDesc, contryCode,startDate,endDate)
VALUES ('Weekly - TY','UK','20160919','20160925')
,('Weekly - LY','UK','20150921','20150927')
,('Weekly - LW','UK','20150912','20150918')
So, corresponding week previous year. The other range is month to date.
Whats the best way to do this? I'd prefer one where i only need to enter one date and the rest can be updated.
Any questions, feel free to ask.
You can always get current system datetime by GETDATE(), and then modify it accordingly by DATEADD()
For example:
SELECT DATEADD(YEAR, -1, GETDATE()) -- Result in 1 year prior the current system datetime.
SELECT DATEADD(MONTH, 13, GETDATE()) -- Result in 13 months after the current system datetime.
In your code snippet you seems to be converting the datetime into yyyymmdd string format (Although I highly doubt the necessity), which can be achieve by a CONVERT:
SELECT CONVERT(VARCHAR, DATEADD(YEAR, -1, GETDATE()), 112)
For example if today is 10/26/2016, then it should show result as 1 year prior to today in yyyymmdd format, 20151026

Get records from a specific hour every day in sql server

I have a requirement to pull records from SQL Server from a specific hour every day, say at 4 PM.
So if I am running query at 3 PM today, it should pull records from previous day 4 PM till today 3 PM (23 hours).
On the other hand, if run query at 4:30 PM today, it should pull query from today 4 PM to 4:30 PM (only for half an hour) and so on
How could I do this in plain SQL in SQL Server?
Here is how I would do it:
SELECT *
FROM TableName
WHERE ColumnName <= GETDATE()
AND ColumnName >=
CASE WHEN DATEPART(HOUR, GETDATE()) < 4 THEN
DATEADD(HH, 4, CAST(CAST(GETDATE()-1 AS date) AS datetime))
ELSE
DATEADD(HH, 4, CAST(CAST(GETDATE() AS date) AS datetime))
END
Points of interest:
CAST(GETDATE() AS date) will return the date part of the current datetime.
Casting back to datetime allows you to use DateAdd to get the hour you want
using -1 with date values subtracts a day from the date (+1 will add a day, of course)
using the CASE...WHEN allows you to write a single where clause that fits both scenarios described in the question.
Please try the below query, i have created it for stored procedures that had been modified on specific date:
Select * from sys.procedures where CONVERT(date,modify_date,101) =
CONVERT(date,DATEADD(DD,-5, GETDATE()),101)
AND DATEPART(hh,modify_date) >= 1 AND DATEPART(hh,modify_date) <= 22
You can pass "CONVERT(date,DATEADD(DD,-5, GETDATE()),101)" GEDATE only instead to - minus five days, that was done only to fetch records for me.
and in hours you can specify the range as you want.
Hope this will work for you.
I think this might help you
select 1 from table where Col1 between case when hour(getdate())>4 then convert(datetime,convert(varchar(20),year(getdate()))+'-'+convert(varchar(20),month(getdate()))+'-'+convert(varchar(20),day(getdate()))+' 04:00') else dateadd(hh,-23,getdate()) end and getdate()

Only filter my time in SQL Server where clause

I am new to SQL and Programming in general. I have a datetime field which I want to use to filter my results but only on the time portion.
For example I need to run a report from 2pm yesterday to 7am current day. I cannot hard code the dates because this report needs to run daily. This Query will run from a stored procedure automatically.
I have tried AND clm.createDtTm > DATEADD(d, -1, GETDATE()), which goes back one day but not the time range I need.
I tried this: AND (datepart(hh, '11:02:54.107') = 7)<--To be honest not even sure what I am doing here.
I am not sure if this is even possible, but if I can get results for one day back I am assuming there has to be a way to narrow that day between hours.
Any help would be appreciated.
Thanks,
Abdul
This should do the trick, it filters out rows that do not fall in the date interval, from 7pm yesterday to 7am today.
WHERE
createDtTm >= DATEADD(HOUR, 14,CAST(DATEADD(DAY,-1, CAST(GETDATE() AS DATE)) AS DATETIME))
AND createDtTm <= DATEADD(HOUR, 7, CAST(CAST(GETDATE() AS DATE) AS DATETIME))
I suggest something like this:
SELECT(DATEADD(d,-1,GETDATE()))
FROM table
WHERE (DATEADD(d,-1,GETDATE())) = rowloadtimestamp
HAVING DATEPART(HH,rowloadtimestamp) BETWEEN 13 AND 24
UNION
SELECT GETDATE()
FROM table
WHERE GETDATE() = rowloadtimestamp
HAVING DATEPART(HH,GETDATE()) BETWEEN 1 AND 7
Assuming you have a rowloadtimestamp field this should work for you.
What do you mean with „I can not hardcode the dates” ? Do you mean the time interval is variable, or is it fixed, or are you referring to the exact dates? I'm not sure I understand.
In case of MySQL you can do something like:
SELECT data, date FROM table WHERE date < DATE_SUB(NOW(), INTERVAL 2 DAY);
This Query will get you the last two days. You can vary the interval by replacing the „2” with a variable if that is possible in your case.

How to add days to the current date?

I am trying to add days to the current date and it's working fine but when I add 360 days to the current date it gives me wrong value.
eg: Current Date is 11/04/2014
And I am adding 360 Days to it, it should give me 11/04/2015, but it is showing the same date 11/04/2014. the year is not changing.
Here is my code:
select dateadd(dd,360,getdate())
Just do-
Select (Getdate()+360) As MyDate
There is no need to use dateadd function for adding or subtracting days from a given date. For adding years, months, hours you need the dateadd function.
select dateadd(dd,360,getdate()) will give you correct date as shown below:
2017-09-30 15:40:37.260
I just ran the query and checked:
Dateadd(datepart,number,date)
You should use it like this:
select DATEADD(day,360,getdate())
Then you will find the same date but different year.
From the SQL Server 2017 official documentation:
SELECT DATEADD(day, 360, GETDATE());
If you would like to remove the time part of the GETDATE function, you can do:
SELECT DATEADD(day, 360, CAST(GETDATE() AS DATE));
In SQL Server 2008 and above just do this:
SELECT DATEADD(day, 1, Getdate()) AS DateAdd;
can try this
select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result
Two or three ways (depends what you want), say we are at Current Date is
(in tsql code) -
DECLARE #myCurrentDate datetime = '11Apr2014 10:02:25 AM'
(BTW - did you mean 11April2014 or 04Nov2014 in your original post? hard to tell, as datetime is culture biased. In Israel 11/04/2015 means 11April2014. I know in the USA 11/04/2014 it means 04Nov2014. tommatoes tomatos I guess)
SELECT #myCurrentDate + 360 - by default datetime calculations followed by + (some integer), just add that in days. So you would get 2015-04-06 10:02:25.000 - not exactly what you wanted, but rather just a ball park figure for a close date next year.
SELECT DateADD(DAY, 365, #myCurrentDate) or DateADD(dd, 365, #myCurrentDate)
will give you '2015-04-11 10:02:25.000'. These two are syntatic sugar (exacly the same). This is what you wanted, I should think. But it's still wrong, because if the date was a "3 out of 4" year (say DECLARE #myCurrentDate datetime = '11Apr2011 10:02:25 AM') you would get '2012-04-10 10:02:25.000'. because 2012 had 366 days, remember? (29Feb2012 consumes an "extra" day. Almost every fourth year has 29Feb).
So what I think you meant was
SELECT DateADD(year, 1, #myCurrentDate)
which gives 2015-04-11 10:02:25.000.
or better yet
SELECT DateADD(year, 1, DateADD(day, DateDiff(day, 0, #myCurrentDate), 0))
which gives you 2015-04-11 00:00:00.000 (because datetime also has time, right?). Subtle, ah?
This will give total number of days including today in the current month.
select day(getDate())
Add Days in Date in SQL
DECLARE #NEWDOB DATE=null
SET #NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)
SELECT DateAdd(5,day(getdate()) this is for adding 5 days to current days.
for eg:today date is 23/08/2018 it became 28/08/2018 by using the above query

How to get one month ago from today in SQL Server 2008?

I´m writing a query where i get the last month, but with the time in zeros (if today is 2013-05-21 then i want to get 2013-04-21 00:00:00.000).
So I tried:
select (dateadd(month,datediff(month,(0),getdate())-1,(0)));
But I get the first day of the previous month.
Then I tried:
select dateadd(month, -1, GETDATE());
I get the right day, but I also get the current time (2013-04-21 11:41:31.090), and I want the time in zeros.
So how should my query be in order to get something like: 2013-04-21 00:00:00.000
Thanks in advance.
In SQL Server 2008 there is the date data type, which has no time attached. You can thus remove the time portion quite easily simply by converting, then performing the DateAdd.
SELECT DateAdd(month, -1, Convert(date, GetDate()));
This will return a date data type. To force it to be datetime again, you can simply add one more Convert:
SELECT Convert(datetime, DateAdd(month, -1, Convert(date, GetDate())));
You may not need the explicit conversion to datetime, though.
Note: "One month ago from today" could be defined in many different ways. The way it works in SQL server is to return the day from the previous month that is the closest to the same day number as the current month. This means that the result of this expression when run on March 31 will be February 28. So, you may not get expected results in certain scenarios if you don't think clearly about the ramifications of this, such as if you performed the one-month calculation multiple times, expecting to get the same day in a different month (such as doing March -> February -> January).
See a live demo at SQL Fiddle
The demo shows the values and resulting data types of each expression.
Try like this..
select Cast(Cast(dateadd(month, -1, GETDATE()) as Date) as Datetime);
You can use this , it's pretty simple and worked for me -
SELECT SUM( amount ) AS total FROM expenses WHERE MONTH( date ) = MONTH( curdate() ) -1
To get the previous month start date and end date
DECLARE #StartDate date;
DECLARE #EndDate date;
select #StartDate= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0)
select #EndDate= DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)
Here are many common dates you may need to pull with logic
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),0) -- Today Midnight
SELECT DATEADD(dd,DATEDIFF(dd,0,GETDATE()),-1) -- Yesterday Midnight
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)) -- First of Last Month
SELECT DATEADD(d,DATEPART(DD,GETDATE()-1),DATEADD(mm, DATEDIFF(m,0,GETDATE())-1,0)) -- Same Day Last Month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) -- Last of Last Month
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) -- First of this month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- Last of this month
SELECT DATEADD(d,0,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- First of next month
SELECT DATEADD(d,DATEPART(DD,GETDATE()-1),DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) -- Same Day Next Month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+2,0)) -- Last of next month
SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+12,0)) -- Last of prior month one year from now
SELECT DATEADD(dd,DATEDIFF(dd,0,DATEADD(DAY, 13-(##DATEFIRST + (DATEPART(WEEKDAY,GETDATE()) %7)), GETDATE())),0) -- Next Friday Midnight

Resources