[Solved] Convert a string to date in SQL Server


I guess you want something like this

DECLARE @str VARCHAR(50)= '1 year 12 months 2 days'
DECLARE @days   INT= LEFT(@str, Charindex(' ', @str)),
        @months INT = Substring(@str, Charindex('months', @str) - 3, 2),
        @years  INT = Substring(@str, Charindex('days', @str) - 3, 2);

WITH days_back
     AS (SELECT Dateadd(day, -@days, Cast(Getdate() AS DATE)) AS day_date),
     month_back
     AS (SELECT Dateadd(month, -@months, day_date) AS month_date
         FROM   days_back)
SELECT Result = Dateadd(year, -@years, month_date)
FROM   month_back 

7

solved Convert a string to date in SQL Server