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());