dynamically changing dates in a temp table - sql-server

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

Related

Date filter on column in sql

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)

TSQL Determine every other Friday from a "seed" date

Greetings StackOverflow Wizards.
SQL datetime calculations always give me trouble. I am trying to determine if an employee's hiredate fell between the last payday of that month and the first of the next month. (I.e. did they get a paycheck in their hire month.
Knowns:
I know our paydays are every other Friday.
I know 01/02/1970 was a Payday, and that date precedes the longest
active employee we have.
I know the hire date of each active employee (pulled from table).
I know (can calculate) the first of the month following the hire
date.
What I cannot seem to wrap my head around is how to use that seed date (01/02/1970) with datediff, dateadd, datepart, etc. to determine if there is a pay date between the hire date in question and the first of the following month.
In pseudo-code, here is what I'm trying to do:
declare #seedDate datetime = '01/02/1970' -- Friday - Payday seed date from which to calculate
declare #hireDate datetime = '09/26/2008' -- this date will actually be pulled from ServiceTotal table
declare #firstOfMonth datetime = DATEADD(MONTH, DATEDIFF(MONTH, 0, #hireDate) + 1, 0) -- the first of the month following #hireDate
declare #priorPayDate datetime -- calculate the friday payday immediately prior to #firstOfMonth
if #priorPayDate BETWEEN #hireDate AND #firstOfMonth
begin
-- do this
end
else
begin
-- do that
end
Using the hard-coded #hireDate above, and the #seedDate to determine every-other-Friday paydays, I know that there was a payday on 9/19/2008 and not another one until 10/03/2008, so the boolean above would be FALSE, and I will "do that" rather than "do this." How do I determine the value of #priorPayDate?
In all my databases where there is a lot going on with dates I create a table with colums for date,day, weekday,month,weeknr,dayof month, etc etc. I then use a procedural programming language or a bunch of handwritten sql to populate this table with every day for a large range of years say 1970 to 2200.
I pack this table 100% and index it heavily. You can then simply join any date to this table and do complex date stuff with simple where clause. So basically you pre calculate a helper table. maybe in you case you add a column to the date helper table with friday since seed column.
hope that makes sense.
Taking a DATEDIFF for days between your #seedDate and #firstOfMonth will give you a total number of days, which you can modulus by number of days between pay periods (14) to get number of days from the last pay period to the #firstOfMonth. You'll run into problems when the 1st is a payday (e.g. next month), which makes a CASE statement necessary:
DECLARE #priorPayDate DATETIME
SET #priorPayDate = CASE
WHEN DATEDIFF(dd, #seedDate, #firstOfMonth) % 14 = 0
THEN DATEADD(dd, -14, #firstOfMonth)
ELSE DATEADD(dd, -(DATEDIFF(dd, #seedDate, #firstOfMonth) % 14), #firstOfMonth)
END

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

sql parameters for date and time

I'm trying to run a query that returns values based on yesterday's date. In this case how many items were shipped out yesterday. This is my query:
shh.SHIP_DATE = dateadd(dd, -1, getdate())
when I run it it doesn't return anything, but when I plug in a date it gives me values:
shh.SHIP_DATE = '2013-12-09'
Is the SHIP_DATE column a date or a datetime? I'm assuming it's a datetime column, but storing only a date value, so when you use getdate() you are going to get the time value as well. You could easily get it working by using the predicate (shh.SHIP_DATE = cast(dateadd(dd, -1, getdate()) as date))
GETDATE() includes the current time as well. You need to truncate the time portion. There's lost of ways to do that - here's one:
shh.SHIP_DATE = DATEADD(dd, DATEDIFF(dd, 0, getdate())-1, 0)
translated - add one less than the number of days between date "0" and today to date "0"

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