Date won't change after using DATEADD() function in SQL Server 2017 - sql

I have a date stored in a string (#cnp=1051597991234) the date being 051597 representing 5/15/1997. I am using the following code to set a date variable with the needed value, in the end to compute the current age.
I used the debugger but somehow it ends up being not set and the diff also returning null.
If someone could help I would be very grateful
declare #cnp varchar(30) = 1051597991234;
declare #age int;
declare #dateBorn date = CAST('1900-01-01' AS DATETIME);
declare #dayBorn int;
declare #monthBorn int;
declare #yearBorn int;
set #dayBorn = cast(substring(#cnp, 2, 2) as int) - 1;
set #monthBorn = cast(substring(#cnp, 4, 2) as int) - 1;
set #yearBorn = cast(substring(#cnp, 6, 2) as int);
set #dateBorn = dateadd(yyyy, #yearBorn, #dateBorn);
set #dateBorn = dateadd(mm, #monthBorn, #dateBorn);
set #dateBorn = dateadd(dd, #dayBorn, #dateBorn);
set #age = datediff(year, getdate(), #dateBorn);

It's declaration problem. Just change this
declare #cnp = 1051597991234
with this
declare #cnp nvarchar(20) ='1051597991234'
and also change the sequence for as from date will be date of birth
set #age =datediff(year,#dateBorn,getdate());

Can I suggest using the DATEFROMPARTS function?
So:
DECLARE #dateBorn DATE =
DATEFROMPARTS(
CAST('19' + SUBSTRING(#cnp,6,2) AS INT)
,CAST(SUBSTRING(#cnp,2,2) AS INT)
,CAST(SUBSTRING(#cnp,4,2) AS INT)
);
DECLARE #age INT =
DATEDIFF(YEAR, GETDATE(), #dateBorn);
Please note that the birthdate strings you have are not Y2K safe, which is why I've put a constant in to assume that they were in the 20th century.
Also note that your dates are in American format, with the month first, day second, and year third.

Related

How to calculate age by day, month and year in in trigger update SQL

I am using this code but something is wrong.
I tried to use many codes but failed to achieve the equation.
I enter to calculate the age add day in day and month in month and year in year
ALTER TRIGGER [dbo].[trg_DeasignTeamMonthly]
ON [dbo].[StudentData]
AFTER INSERT, DELETE, UPDATE
AS
BEGIN
UPDATE dbo.StudentData
SET [Day] = DATEDIFF(DAY, StudentData.DateOfBirth,[dbo].StudentData.DateToDay) / 365
UPDATE dbo.StudentData
SET [Month] = MONTH([dbo].StudentData.DateToDay) - 1
UPDATE dbo.StudentData
SET [Year] = YEAR([dbo].StudentData.DateToDay) - YEAR([dbo].StudentData.DateOfBirth)
END
I create a stored procedure for calculating for this purpose, you could using it in anywhere that you need (trigger, other stored procedure ,)
CREATE PROCEDURE CalcDurationRange
#StartDT DATETIME,
#EndDT DATETIME,
#Year INT OUT,
#Month INT OUT,
#Day INT OUT
AS
DECLARE #xDate DATETIME = DATEADD(YEAR,YEAR(#EndDT)-YEAR(#StartDT),#StartDT)
IF(#xDate>#EndDT)
SET #xDate = DATEADD(YEAR,-1,#xDate)
SET #Year = DATEDIFF(YEAR,#StartDT,#xDate)
SET #Month = DATEDIFF(MONTH,#xDate,#EndDT)
IF(DATEADD(MONTH,#Month,#xDate)>#EndDT)
SET #Month = #Month -1
SET #Day = DATEDIFF(DAY,DATEADD(MONTH,#Month,#xDate),#EndDT)
GO
sample of using this SP :
DECLARE #xYear INT, #xMonth INT, #xDay INT
EXEC CalcDurationRange
'1987-12-01',
'2021-10-01',
#xYear OUT,
#xMonth OUT,
#xDay OUT
PRINT #xYear
PRINT #xMonth
PRINT #xDay

How to create a Date in SQL Server given the Day, Month and Year as Integers

FOR Example if I have:
DECLARE #Day int = 25
DECLARE #Month int = 10
DECLARE #Year int = 2016
I want to return
2016-10-25
As Date or datetime
In SQL Server 2012+, you can use datefromparts():
select datefromparts(#year, #month, #day)
In earlier versions, you can cast a string. Here is one method:
select cast(cast(#year*10000 + #month*100 + #day as varchar(255)) as date)
In SQL Server 2012+, you can use DATEFROMPARTS():
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT DATEFROMPARTS (#Year, #Month, #Day);
In earlier versions, one method is to create and convert a string.
There are a few string date formats which SQL Server reliably interprets regardless of the date, language, or internationalization settings.
A six- or eight-digit string is always interpreted as ymd. The month
and day must always be two digits.
https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql
So a string in the format 'yyyymmdd' will always be properly interpreted.
(ISO 8601-- YYYY-MM-DDThh:mm:ss-- also works, but you have to specify time and therefore it's more complicated than you need.)
While you can simply CAST this string as a date, you must use CONVERT in order to specify a style, and you must specify a style in order to be deterministic (if that matters to you).
The "yyyymmdd" format is style 112, so your conversion looks like this:
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
And it results in:
2016-10-25
Technically, the ISO/112/yyyymmdd format works even with other styles specified. For example, using that text format with style 104 (German, dd.mm.yyyy):
DECLARE #Year int = 2016, #Month int = 10, #Day int = 25;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),104);
Also still results in:
2016-10-25
Other formats are not as robust. For example this:
SELECT CASE WHEN CONVERT(date,'01-02-1900',110) = CONVERT(date,'01-02-1900',105) THEN 1 ELSE 0 END;
Results in:
0
As a side note, with this method, beware that nonsense inputs can yield valid but incorrect dates:
DECLARE #Year int = 2016, #Month int = 0, #Day int = 1025;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
Also yields:
2016-10-25
DATEFROMPARTS protects you from invalid inputs. This:
DECLARE #Year int = 2016, #Month int = 10, #Day int = 32;
SELECT DATEFROMPARTS (#Year, #Month, #Day);
Yields:
Msg 289, Level 16, State 1, Line 2 Cannot construct data type date,
some of the arguments have values which are not valid.
Also beware that this method does not work for dates prior to 1000-01-01. For example:
DECLARE #Year int = 900, #Month int = 1, #Day int = 1;
SELECT CONVERT(date,CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),112);
Yields:
Msg 241, Level 16, State 1, Line 2 Conversion failed when converting
date and/or time from character string.
That's because the resulting string, '9000101', is not in the 'yyyymmdd' format. To ensure proper formatting, you'd have to pad it with leading zeroes, at the sacrifice of some small amount of performance. For example:
DECLARE #Year int = 900, #Month int = 1, #Day int = 1;
SELECT CONVERT(date,RIGHT('000' + CONVERT(varchar(50),(#Year*10000 + #Month*100 + #Day)),8),112);
Results in:
0900-01-01
There are other methods aside from string conversion. Several are provided in answers to "Create a date with T-SQL". A notable example involves creating the date by adding years, months, and days to the "zero date".
(This answer was inspired by Gordon Linoff's answer, which I expanded on and provided additional documentation and notes.)
Old Microsoft Sql Sever (< 2012)
RETURN dateadd(month, 12 * #year + #month - 22801, #day - 1)
The following code should work on all versions of sql server I believe:
SELECT CAST(CONCAT(CAST(#Year AS VARCHAR(4)), '-',CAST(#Month AS VARCHAR(2)), '-',CAST(#Day AS VARCHAR(2))) AS DATE)
Simple and most flexible solution
Use FORMAT function to make any type of format you like.
Here is copy paste working example:
DECLARE #year int = 2021, #month int = 12, #day int = 16
DECLARE #date varchar(20)
SET #date = cast((format(#year,'####') +'-'+format(#month,'##')+'-'+format(#day,'##')) as date)
SELECT #date
It will also display leading zeros for days and months.
So, you can try this solution:
DECLARE #DAY INT = 25
DECLARE #MONTH INT = 10
DECLARE #YEAR INT = 2016
DECLARE #DATE AS DATETIME
SET #DATE = CAST(RTRIM(#YEAR * 10000 + #MONTH * 100 + #DAY) AS DATETIME)
SELECT REPLACE(CONVERT(VARCHAR(10), #DATE, 102), '.', '-') AS EXPECTDATE
Or you can try this a few lines of code:
DECLARE #DAY INT = 25
DECLARE #MONTH INT = 10
DECLARE #YEAR INT = 2016
SELECT CAST(RTRIM(#YEAR * 10000 +'-' + #MONTH * 100+ '-' + #DAY) AS DATE) AS EXPECTDATE
select convert(varchar(11), transfer_date, 106)
got me my desired result of date formatted as 07 Mar 2018
My column 'transfer_date' is a datetime type column and I am using SQL Server 2017 on azure
CREATE DATE USING MONTH YEAR IN SQL::
DECLARE #FromMonth int=NULL,
#ToMonth int=NULL,
#FromYear int=NULL,
#ToYear int=NULL
/**Region For Create Date**/
DECLARE #FromDate DATE=NULL
DECLARE #ToDate DATE=NULL
SET #FromDate=DateAdd(day,0, DateAdd(month, #FromMonth - 1,DateAdd(Year, #FromYear-1900, 0)))
SET #ToDate=DateAdd(day,-1, DateAdd(month, #ToMonth - 0,DateAdd(Year, #ToYear-1900, 0)))
/**Region For Create Date**/
For SQL Server 2008 users, I made a custom function:
CREATE FUNCTION sql2012_datefromparts
(
#Year int, #Month int, #Day int
)
RETURNS DATETIME
AS
BEGIN
RETURN convert(datetime,convert(varchar,#year)+right('0'+convert(varchar,#month),2)+right('0'+convert(varchar,#day),2))
END
GO
To use it:
DECLARE #day int=29, #month int=10, #year int=1971
SELECT dbo.sql2012_datefromparts(#year,#month,#day)

Setting specific dates for a variable in SQL

I would lake to specify a specific datetime variable to be used. The code would look something like this:
Declare #Year = int
Declare #JanDate = Datetime
Set #JanDate = ???
I would like to set #JanDate to Month=1, Day =25, Year = #Year. Not sure what to put in for that?
For those who are using SQL Server 2012, use one of the DATEFROMPARTS, DATETIMEFROMPARTS, DATETIME2FROMPARTS, OR SMALLDATETIMEFROMPARTS functions. You are on SQL 2005, so these functions are not available, but I am including them anyway in case someone on 2012 or higher finds this question in the future.
For example:
declare #Year int = 2014
declare #JanDate datetime
select #JanDate = DATETIMEFROMPARTS(#Year, 1, 25, 0, 0, 0, 0)
For the poster and those of us still using SQL Server 2005, you can concatenate a string together and convert that to a date:
declare #Year int = 2014
declare #JanDate datetime
select #JanDate = CAST(CAST(#Year as varchar) + '-1-25' as varchar)
Or, see the answer to this question for a possibly more efficient way using multiple DATEADD functions.
I don't like casting strings to dates. Neither should you.
If you using SQL Server 2012 or later then you can use the answersuggested by Paul Williams i.e. DateFromParts or similar functions.
For earlier versions here's the method I would use:
DECLARE #Year int;
DECLARE #JanDate datetime;
SET #Year = 2014;
SET #JanDate = DateAdd(dd, 25 - 1, DateAdd(yy, #Year - 1900, '1900-01-01'));
SELECT #JanDate;
It might seem overly complicated to some, but the way in which it performs the action is much more pleasing [to me] as it uses nothing but dates and integers.
Starting at SQL Servers base date 1900-01-01 we add on the number of years supplied (correcting by 1900 years ;-))
Then we add on the number of days (again, a correction of 1 day is required as the date we're working with is already the 1st of the month so adding 25 = 26, not the 25 we want).
Here's some supplementary code that you might find useful. Supply it any year, month and day it it will work it out for you.
If a user supplies "invalid" values (e.g. 2014-02-31 - there is no 31st of February) then the function will not fail, unlike a text to date casting. Instead it will provide the result 2014-03-03 which is 31 days after 1st Feb.
This logic might not please some people but it has always worked for me.
Enough waffling, here's the code:
DECLARE #y int
, #m int
, #d int;
SET #y = 2014;
SET #m = 6;
SET #d = 22;
SELECT DateAdd(dd, #d - 1, DateAdd(mm, #m - 1, DateAdd(yy, #y - 1900, '1900-01-01')));
-End transmission-
Your DECLARE statements may be incorrect depending on your version of SQL. The following should work (you'll just need to change #Year for the year you want):
DECLARE #Year int
DECLARE #JanDate Datetime
SET #Year=2013
SET #JanDate='1/25/'+CAST(#Year AS VARCHAR)
Declare #Year int;
SET #Year = 2013;
Declare #JanDate Datetime;
SET #JanDate = CAST(
CAST(#Year AS NVARCHAR(4)) + CAST('01' AS NVARCHAR(2)) + CAST('25' AS NVARCHAR(2))
AS DATETIME)
SELECT #JanDate
RESULT: 2013-01-25 00:00:00.000
Or simply
Declare #Year int;
SET #Year = 2013;
Declare #JanDate Datetime;
SET #JanDate = CAST(
CAST(#Year AS NVARCHAR(4)) + '01' + '25'
AS DATETIME)
SELECT #JanDate
RESULT: 2013-01-25 00:00:00.000

SQL Server : setting two variables month and year for previous month, year roll over safe

I'm trying to basically dynamically set two variables (#month and #year) to be whatever the previous month and year were.
So in today's case #month = 7 and #year = 2012
But I want something safe for the year roll around, so if it's 1/1/2013 I would get #month = 12 and #year = 2012.
Thanks!
This is what I have.
declare #month int
declare #year int
set #month = month (getDate ())-1
set #year = 2012
You can use DATEADD to subtract a month from the current date, then grab the MONTH and YEAR portions:
DECLARE #monthAgo dateTime
DECLARE #month int
DECLARE #year int
SET #monthAgo = DATEADD(month, -1, GETDATE())
SET #month = MONTH(#monthAgo)
SET #year = YEAR(#monthAgo)
Shown in steps. You can modify the value assigned to #Now to test.
DECLARE #Now DateTime = GETDATE();
DECLARE #Then DateTime = DATEADD(Month, -1, #Now);
DECLARE #Month Int = DATEPART(Month, #Then);
DECLARE #Year Int = DATEPART(Year, #Then);
SELECT #Month, #Year;
can you not just add, after what you already have:
if #month = 0
begin
set #month = 12
set #year = #year - 1
end
As a single query, this gives the first day of last month:
select DATEADD(month,DATEDIFF(month,'20010101',CURRENT_TIMESTAMP),'20001201')
You can, if you choose, pull that apart into two separate variables, but why bother? (I assume the rest of what you're doing is working with datetimes also, rather than ints)
The two datetime strings above are selected because they have the desired relationship between them - that the second starts 1 month before the first.
Try this
declare #month int
declare #year int
Declare #dt datetime=getdate()
set #month = DATEPART(mm,DATEADD(mm,-1,#dt))
select #month
set #year = DATEPART(yy,DATEADD(mm,-1,#dt))
select #year

SQL: How to produce next date given month and day

In my table I have a Month(tinyint) and a Day(tinyint) field. I would like to have a function that takes this month and day and produces a datetime for the next date(including year) given this month and day.
So if I had Month = 9, Day = 7 it would produce 9/7/2009.
If I had Month 1, Day 1 it would produce 1/1/2010.
something like this would work. It's variation on your method, but it doesn't use the MM/DD/YYYY literal format, and it won't blowup against bad input (for better or for worse).
declare #month tinyint
declare #day tinyint
set #month = 9
set #day = 1
declare #date datetime
-- this could be inlined if desired
set #date = convert(char(4),year(getdate()))+'0101'
set #date = dateadd(month,#month-1,#date)
set #date = dateadd(day,#day-1,#date)
if #date <= getdate()-1
set #date = dateadd(year,1,#date)
select #date
Alternatively, to create a string in YYYYMMDD format:
set #date =
right('0000'+convert(char(4),year(getdate())),4)
+ right('00'+convert(char(2),#month),2)
+ right('00'+convert(char(2),#day),2)
Another method, which avoids literals all together:
declare #month tinyint
declare #day tinyint
set #month = 6
set #day = 24
declare #date datetime
declare #today datetime
-- get todays date, stripping out the hours and minutes
-- and save the value for later
set #date = floor(convert(float,getdate()))
set #today = #date
-- add the appropriate number of months and days
set #date = dateadd(month,#month-month(#date),#date)
set #date = dateadd(day,#day-day(#date),#date)
-- increment year by 1 if necessary
if #date < #today set #date = dateadd(year,1,#date)
select #date
Here is my sql example so far. I don't really like it though...
DECLARE #month tinyint,
#day tinyint,
#date datetime
SET #month = 1
SET #day = 1
-- SET DATE TO DATE WITH CURRENT YEAR
SET #date = CONVERT(datetime, CONVERT(varchar,#month) + '/' + CONVERT(varchar,#day) + '/' + CONVERT(varchar,YEAR(GETDATE())))
-- IF DATE IS BEFORE TODAY, ADD ANOTHER YEAR
IF (DATEDIFF(DAY, GETDATE(), #date) < 0)
BEGIN
SET #date = DATEADD(YEAR, 1, #date)
END
SELECT #date
Here's a solution with PostgreSQL
your_date_calculated = Year * 10000 + Month * 100 + Day
gives you a date like 20090623.
select cast( cast( your_date_calculated as varchar ) as date ) + 1
Here's my version. The core of it is just two lines, using the DATEADD function, and it doesn't require any conversion to/from strings, floats or anything else:
DECLARE #Month TINYINT
DECLARE #Day TINYINT
SET #Month = 9
SET #Day = 7
DECLARE #Result DATETIME
SET #Result =
DATEADD(month, ((YEAR(GETDATE()) - 1900) * 12) + #Month - 1, #Day - 1)
IF (#Result < GETDATE())
SET #Result = DATEADD(year, 1, #Result)
SELECT #Result