TSQL: How to change date if date falls between current year dates? - sql-server

I need to change a passed variable date if the date falls under the current year Nov 1st to Dec 31st
How to do this in TSQL?
Example:
Example #1
#ip_batch_date = '2020-12-01T00:00:00'
check #ip_batch_date >=' '2020-11-01T00:00:00' AND #ip_batch_date<='2020-12-31T00:00:00'
Then #ip_batch_date = '2021-01-01T00:00:00'
Example #2
#ip_batch_date = '2021-11-15T00:00:00'
check #ip_batch_date >='2021-11-01T00:00:00' AND #ip_batch_date<='2021-12-31T00:00:00'
Then #ip_batch_date = '2022-01-01T00:00:00'

Assuming you already have a passed in date variable called #ip_batch_date, off the top of my head I would use something like
IF (YEAR(#ip_batch_date) = YEAR(GetDate()) AND MONTH(#ip_batch_date) BETWEEN 11 AND 12)
SET #ip_batch_date = DATEFROMPARTS(YEAR(GetDate())+1,1,1);
If instead of a passed in date, you were writing a query that was going to process lots of rows with a date column in them that you wanted to subject this logic to, it would be best not to have ip_date_column converted by a function, but rather to leave the date column bare and compare it to two constructed dates, like this:
CASE WHEN my_date_column BETWEEN DATEFROMPARTS(YEAR(GetDate()),11,1)
DATEFROMPARTS(YEAR(GetDate()),12,31)
THEN DATEFROMPARTS(YEAR(GetDate())+1,1,1);
ELSE my_date_column
END
Finally, if my_date_column was a datetime or datetime2 column instead of just a date, make sure you you datetimefromparts or datetime2fromparts instead, and add the time in as well to avoid last day boundary issues

If I understood your question correctly:
DECLARE #Date DATETIME
SET #Date = '2020-12-01T00:00:00'
SET #Date = CASE WHEN RIGHT(CONVERT(VARCHAR(8), #Date, 112), 4) >= 1101 THEN DATEADD(yy, DATEDIFF(yy, 0, #Date) + 1, 0) ELSE #Date END
SELECT #Date
-- Output : 2021-01-01 00:00:00.000
SET #Date = '2021-12-01T00:00:00'
SET #Date = CASE WHEN RIGHT(CONVERT(VARCHAR(8), #Date, 112), 4) >= 1101 THEN DATEADD(yy, DATEDIFF(yy, 0, #Date) + 1, 0) ELSE #Date END
SELECT #Date
-- Output : 2022-01-01 00:00:00.000

DECLARE #IP_BATCH_DATE DATETIME= '2020-12-01T00:00:00'
IF #ip_batch_date >= '2020-11-01T00:00:00' AND #ip_batch_date<='2020-12-31T00:00:00'
BEGIN
SELECT datefromparts(YEAR(GETDATE()), 1, 1)
END
ELSE
BEGIN
SELECT #ip_batch_date
END

Related

SQL convert date dmmyyyy and ddmmyy to yyyy-mm-dd

I have the following problem.
I have some dates with the following format '15122019' and I need it in this format 2019-12-15, which I already solved it in the following way.
select convert (date, Stuff(Stuff('15122018',5,0,'.'),3,0,'.'),104)
The real problem is when the dates come like this '3122019' the conversion can not be done because the length is shorter. Is ther e another way to do it? I've been trying to solve it for several hours. And another question, can this query be parameterized?
Try this:
DECLARE #date VARCHAR(20)
SET #date ='3122019'
IF(LEN(#date) = 8)
BEGIN
SET #date = Stuff(Stuff(#date,5,0,'.'),3,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
ELSE IF(LEN(#date) = 7)
BEGIN
SET #date = Stuff(Stuff(#date,4,0,'.'),2,0,'.');
IF(ISDATE(#date)=1)
BEGIN
SELECT CONVERT(DATE, #date , 103);
END
ELSE
BEGIN
SET #date = Stuff(Stuff(#date,4,0,'.'),3,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
END
ELSE IF(LEN(#date) = 6)
BEGIN
SET #date = Stuff(Stuff(#date,3,0,'.'),2,0,'.');
SELECT CONVERT(DATE, #date , 103);
END
You can add 0 to the left and take 8 chars with right. like RIGHT('0'+'15122018',8). it work with 15122018 and 3122018
select convert (date, Stuff(Stuff( RIGHT('0'+'15122018',8) ,5,0,'.'),3,0,'.'),104)
Such conversation can be achieved by:
Casting integer value to DATE using intermediate FORMAT transformation to a recognizable for conversation string pattern.
style 105 applied to match the input as dd-mm-yyyy
style 05 to match dd-mm-yy
SQL:
-- input format: dmmyyyy
SELECT CONVERT(DATE, FORMAT(3012019, '##-##-####'), 105)
-- result: 2019-01-03
-- input format: dmmyy
SELECT CONVERT(DATE, FORMAT(30119, '##-##-##'), 05)
-- result: 2019-01-03
This will work fine with a single (and double) digit day number, however, it indeed requires a double-digit month

Replace only the date part

This question may be duplicate sorry for it,As I could not able to find any solution in web till now so am Posting this
I need to create a SQL server functions where I need to replace only the date part from the actual date ..
For example if the actual date is 01/10/2016 means I need to update the actual date to 15/10/2016 the date part alone is replaced from 01 to 15 I need to achieve this, please help me in solving this as am very new to SQL SERVER
DECLARE #actual_due_date INT = 5;
DECLARE #invoice_date DATETIME = '20161210';
DECLARE #due_date DATETIME;
SET #due_date=DATEADD(DAY,#actual_due_date-DATEPART(DAY,#invoice_date),#invoice_date);
SELECT #due_date;
This prints out
2016-12-05 00:00:00.000
Here's another way to do it:
DECLARE #oldDate DATETIME = '2016-10-17 10:29:22'
DECLARE #replacingDate DATE = '2016-10-15'
DECLARE #newDate DATETIME
SET #newDate = CONVERT(datetime, CONVERT(varchar, #replacingDate)+' '+ LEFT(CONVERT(varchar, CONVERT(time, #oldDate)), 8))
SELECT #newDate
--UPDATE TableA
--SET FieldX = CONVERT(datetime, CONVERT(varchar, #replacingDate)+' '+ LEFT(CONVERT(varchar, CONVERT(time, #oldDate)), 8))
--WHERE SomeCondition
Don't know, what you really try to achieve, but you could try this:
DECLARE #OtherDate DATETIME = {ts'2016-02-05 12:00:00'}; --Some day in February, 12 o'clock
DECLARE #actualDate DATETIME = GETDATE(); --current day and time
--This comes back with the other date, but the actual time
SELECT CAST(CAST(#OtherDate AS date) AS datetime) + CAST(CAST(#actualDate AS time) AS datetime);
Not sure of the purpose, why you are replacing it.
Here is one way:
Declare #date date = '01/10/2016'
Select Replace(Convert(varchar(20), #date, 101), '01/', '15/') AS ReplacedDate
-- 15/10/2016

How to get date from yyyy-mm-dd to yyyy-mm-dd in SQL?

I want to get date from yyyy-mm-dd to yyyy-mm-dd in SQL.
Example: I have two parameter #startdate : 2015-12-28 and #enddate : 2016-01-02, and database in SQLServer, datatype is varchar(10)
DATE_ORDER
28-12-2015
30-12-1996
29-12-2016
30-12-1997
24-12-2015
27-12-1993
03-01-2016
01-01-1992
02-01-2016
etc...
Ok,now I want to get data from #startdate : 2015-12-28 and #enddate : 2016-01-02. I use SELECT * FROM TABLE_X WHERE DATE_ORDER >= #startdate AND DATE_ORDER <= #enddate . But the results are not what I expected. Here are the results I want
28-12-2015
30-12-1996
29-12-2016
30-12-1997
01-01-1992
02-01-2016
I think to solve this problem, I need to do two things :
First, get date range from #startdate to #enddate , in here 28/12/2015, 29/12/2015, 30/12/2015, 31/12/2015, 01/01/2016, 02/01/2016.
The second: get the date in database same in range 28/12, 29/12, 30/12, 31/12, 01/01, 02/01, ignoring the year.
Can you give me some ideas about this ?
Your actual format is "105-italian" find details here.
You can convert your existing VARCHAR(10)-values with this line to real datetime
SELECT CONVERT(DATETIME,YourColumn,105)
Next thing to know is, that you should not use BETWEEN but rather >=StartDate AND < NakedDateOfTheFollowingDay to check date ranges
So to solve your need Get date-range from 2015-12-28 to 2016-01-02 you might do something like this:
DECLARE #Start DATETIME={d'2015-12-28'};
DECLARE #End DATETIME={d'2016-01-02'};
SELECT *
FROM YourTable
WHERE CONVERT(DATETIME,YourDateColumn,105)>=#Start AND CONVERT(DATETIME,YourDateColumn,105)<#End+1
Attention Be aware, that the conversion lets your expression be not sargable. No index will be used.
Better was to store your date as correctly typed data to avoid conversions...
Try this query
SET DATEFIRST 1
DECLARE #wk int SET #wk = 2
DECLARE #yr int SET #yr = 2011
--define start and end limits
DECLARE #todate datetime, #fromdate datetime
SELECT #fromdate = dateadd (week, #wk, dateadd (YEAR, #yr-1900, 0)) - 4 -
datepart(dw, dateadd (week, #wk, dateadd (YEAR, #yr-1900, 0)) - 4) + 1
SELECT #todate = #fromdate + 6
;WITH DateSequence( Date ) AS
(
SELECT #fromdate AS Date
UNION ALL
SELECT dateadd(DAY, 1, Date)
FROM DateSequence
WHERE Date < #todate
)
--select result
SELECT * FROM DateSequence OPTION (MaxRecursion 1000)
So, after the 2nd or 3rd edit, it slowly becomes clear, what you want (i hope).
So you REALLY WANT to get the dates with the year beeing ignored.
As someone pointed out already, date-values are stored internally not as string, but as internal datatype date (whatever that is in memory, i don't know).
If you want to compare DATES, you cannot do that with ignorance of any part. If you want to, you have to build a NEW date value of day and month of given row and a hard coded year (2000 or 1 or whatever) for EVERY row.
SELECT * FROM TABLE_X WHERE convert(date,'2000' + substring(convert(char(8),convert(datetime, 'DATE_ORDER', 105),112),5,4),112) >= #startdate AND convert(date,'2000' + substring(convert(char(8),convert(datetime, 'DATE_ORDER', 105),112),5,4),112) <= #enddate
If your startdate and enddate go OVER sylvester, you have to do 2 queries, on from startdate to 1231, one from 0101 to enddate.

How to calculate difference between two dates in workdays

I need to calculate difference in workdays between two dates. Is there a built in function for this in SQL Server? Can someone please provide an example on how to do this?
Here is something I wrote quickly. Just encapsulate it into a function or whatever you need.
declare #StartDate datetime
declare #EndDate datetime
declare #TotalDiff int
declare #NumberOfWeekends int
SET #StartDate = '3/12/2013'
SET #EndDate = '3/22/2013'
SET #NumberOfWeekends = 0
SET #TotalDiff = DATEDIFF(d,#StartDate, #EndDate)
If #TotalDiff > 7
SET #NumberOfWeekends = #TotalDiff / 7
else if DATEPART(dd, #EndDate) < DATEPART(DD, #StartDate)
SET #NumberOfWeekends = 1
select (#TotalDiff - 2*#NumberOfWeekends) as TotalWorkDays
No, there is nothing built in to SQL Server to directly give you number of working days between two dates, however there are a few built-in functions which will enable you to write one.
Firstly, a few caveats
The world cannot agree what a "Working Day" is. For most of us it's Saturday and Sunday. For most of the Middle East it's Friday & Saturday (with Sunday being a normal working day)
The world most certainly cannot agree on what constitutes a public holiday, which are almost always considered non-working days.
You have not specified how you would like to handle these cases so lets make some assumptions:
Saturday and Sunday will be non-working days
Public holidays will not be taken into acount
Now, determining if a particular days is saturday or sunday in sql is easy, given a #date of type DateTime:
IF DATENAME(dw,#date) IN ('Saturday','Sunday')
With that in mind, given a start and end date, you can just count incrementally from #startDate to #endDate
DECLARE #startDate DATETIME = '2013-01-01'
DECLARE #endDate DATETIME = '2013-01-20'
DECLARE #currDate DATETIME = #startDate
DECLARE #numDays INT = 0
WHILE #currDate<#endDate
BEGIN
IF DATENAME(dw,#currDate) NOT IN ('Saturday','Sunday')
SET #numDays = #numDays + 1
SET #currDate = DATEADD(day,1,#currDate)
END
SELECT #numDays
Note: This is non-inclsive so wont count #endDate. You could change it to be inclusive by changing WHILE #currDate<#endDate to WHILE #currDate<=#endDate
My solution does not count the #EndDate, so if you need to change that, just add 1 to #d2.
First, I calculate the number of days from an "initial" day (which happens to be 1/1/1900, a Monday) to #StartDate and #EndDate:
DECLARE #d1 int = DATEDIFF(Day, 0, #StartDate);
DECLARE #d2 int = DATEDIFF(Day, 0, #EndDate);
Then, the total number of days between #StartDate and #EndDate is:
#d2 - #d1
From this, I substract the number of Sundays and the number of Saturdays in the interval, each calculated as a difference simlar to the total days, but now for whole weeks (7 days). To get the number of whole weeks, I use integer division by 7 and the fact that the "initial" day (0) is a Monday. The number of Sundays in the interval is
#d2/7 - #d1/7
and the number of Saturdays is
(#d2+1)/7 - (#d1+1)/7
Putting all together, my solution is:
DECLARE #StartDate DATETIME = '20180101'
DECLARE #EndDate DATETIME = '20180201'
DECLARE #d1 int = DATEDIFF(Day, 0, #StartDate)
DECLARE #d2 int = DATEDIFF(Day, 0, #EndDate)
SELECT #d2 - #d1 - (#d2/7 - #d1/7) - ((#d2+1)/7 - (#d1+1)/7) AS workdays

In TSQL, how would you convert from an int to a datetime and give the age?

What would be the sql for the following,
I have a date of birth in an int field,
ie YYYYMMDD = 19600518
I would like to get the age.
None of the other answers are actually calculating age. They're calculating the number of year boundaries and not taking the birthday into account.
To calculate the age, you'll need to do something like this:
DECLARE #d DATETIME
SET #d = CONVERT(DATETIME, CONVERT(VARCHAR(8), 19600518), 112)
SELECT DATEDIFF(year, #d, GETDATE())
- CASE WHEN DATEADD(year, DATEDIFF(year, #d, GETDATE()), #d) <= GETDATE()
THEN 0 ELSE 1 END AS Age
Most of the other answers are not calculating age - just whole years (e.g. Jan 1 2009 is one "year" after Dec 31 2008). Thus, if you use most of the calculations on this page, you will return an incorrect age for half of the year, on average. Luke is the only person who has seen this but his answer strikes me as too complicated - there is an easier way:
Select CAST(DATEDIFF(hh, [birthdate], GETDATE()) / 8766 AS int) AS Age
(NOTE: Thanks go to 'Learning' for making a great catch on my original algorithm - this is a revision that uses hours instead of days)
Because the rounding here is very granular, this is almost perfectly accurate for every day of every year. The exceptions are so convoluted that they are almost humorous: every fourth year the age returned will be one year too young if we A) ask for the age before 6:00 AM, B) on the person's birthday and C) their birthday is after February 28th. Of course, depending on what time someone was born this might 'technically' be correct! In my setting, this is a perfectly acceptable compromise.
Here is a loop that prints out ages to show that this works.
Declare #age int;
Declare #BirthDate datetime;
Declare #Year int;
Set #Year = 2008;
WHILE (#Year > 1930)
BEGIN
-- Put today's date where you see '-03-18'
SET #BirthDate = CAST(Cast(#Year as varchar(4)) + '-03-18' AS DATETIME)
SELECT #age=CAST(DATEDIFF(hh, #BirthDate, GETDATE()) / 8766 AS int);
Print Cast(#Year as varchar) + ' Age: ' + Cast(#age as varchar);
Set #Year = #Year - 1;
END;
Finally, this is the version that will also convert Paul's integer date to a real date:
CAST(DATEDIFF(hh, Convert(Datetime, Convert(varchar(8), [birthdate]), 112), GETDATE()) / 8766 AS int) AS Age
DECLARE #dateSt VARCHAR(8)
DECLARE #startDt DATETIME
-- Set the start date string
SET #dateSt = '19600518'
-- Make it a DATETIME (the ISO way)
SET #startDt = CAST(SUBSTRING(#dateSt, 1, 4) + '-' +
SUBSTRING(#dateSt, 5, 2) + '-' +
SUBSTRING(#dateSt, 7, 2) AS DATETIME)
-- Age in Days
SELECT DATEDIFF(D, #startDt, getdate())
Age in years :
select datediff(YY, convert(datetime, convert(varchar, 19600518)), getdate())
[EDIT]
-- I forgot to declare the variables
declare #birthday datetime;
set #birthday = convert(datetime,convert(varchar, 19600518), 112);
declare #datetoday datetime;
set #datetoday = getdate();
select
(
CASE
WHEN dateadd(year, datediff (year, #birthday, #datetoday), #birthday) <= #datetoday
THEN datediff (year, #birthday, #datetoday)
ELSE datediff (year, #birthday, #datetoday) - 1
END) as age;
Here's a one-liner way to do it:
CONVERT(DATETIME, CONVERT(VARCHAR(8),19600518), 112)
But beware! This relies on T-SQL, and probably won't work in other SQL environments.
Please note that the "style" of 112 is simply the "ISO" date format of yyyymmdd. (Something I found in some CONVERT documentation.)
This is a reason why you should NOT ever store dates as anything except a datetime datatype. The best fix is to change your datatype and convert all the dates once (wouldn't be surprised if there are few invalid ones in there either). then you never have to do these workarounds again.
I worked it out and got same as #Learning
select dob, datediff(year, convert(datetime, convert(varchar(8),[dob])) ,getdate()) as age
from [mytable]
where IsDate(convert(varchar(8),[dob])) = 1
NB. I needed the IsDate as well as there were some invalid dates in the data.
Edit. Here is an article from SQLServerCentral on calculating age.

Resources