在SQL Server中将字符串转换为日期

时间:2016-03-01 15:59:38

标签: sql sql-server

我遇到一个问题,我需要将字符串转换为日期,如

11年10个月12天到SQL Server中的日期。

请帮助任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

我想你想要这样的东西

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 

答案 1 :(得分:0)

declare @fuzzy_date varchar(255) = '11 years 10 months 12 days'

declare @date date
declare @startdate date = '1999-12-31'
declare @today_to_before date = getdate()
declare @today_to_after date = getdate()

declare @years int, @months int, @days int, @foo varchar(255)

Set @years = left(@fuzzy_date, charindex('years', @fuzzy_date) - 1)

Select @fuzzy_date = right(@fuzzy_date, len(@fuzzy_date) - charindex('years', @fuzzy_date) - 5)

select @months = left(@fuzzy_date, charindex('months', @fuzzy_date) - 1)

Select @days = replace(right(@fuzzy_date, len(@fuzzy_date) - charindex('months', @fuzzy_date) - 6), 'days', '')

Select @years, @months, @days

Set @date = dateadd(yy, @years, @startdate)
Set @date = dateadd(mm, @months, @date)
Set @date = dateadd(dd, @days, @date)


Set @today_to_after = dateadd(yy, @years, @today_to_after)
Set @today_to_after = dateadd(mm, @months, @today_to_after)
Set @today_to_after = dateadd(dd, @days, @today_to_after)

Set @today_to_before = dateadd(yy, -@years, @today_to_before)
Set @today_to_before = dateadd(mm, -@months, @today_to_before)
Set @today_to_before = dateadd(dd, -@days, @today_to_before)
Select @date,@today_to_after,@today_to_before