Search code examples
sqlsql-serversql-date-functionssqldatetime

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


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

Solution

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