这可以使用如下自定义代码来完成 - 我假设您使用的值是人们的年龄,并且您正在尝试根据他们今天的年龄计算出他们的出生日期。
你可以在这里看到下面的代码:http ://sqlfiddle.com/#!3/c757c/2
create function dbo.AgeToDOB(@age nvarchar(32))
returns datetime
as
begin
declare @pointer int = 0
, @pointerPrev int = 1
, @y nvarchar(6)
, @m nvarchar(6)
, @w nvarchar(6)
, @d nvarchar(6)
, @result datetime = getutcdate() --set this to the date we're working to/from
--convert various ways of expressing units to a standard
set @age = REPLACE(@age,'Years','Y')
set @age = REPLACE(@age,'Year','Y')
set @age = REPLACE(@age,'Months','M')
set @age = REPLACE(@age,'Month','M')
set @age = REPLACE(@age,'Weeks','W')
set @age = REPLACE(@age,'Week','W')
set @age = REPLACE(@age,'Days','D')
set @age = REPLACE(@age,'Day','D')
set @pointer = isnull(nullif(CHARINDEX('Y',@age),0),@pointer)
set @y = case when @pointer > @pointerprev then SUBSTRING(@age,@pointerprev,@pointer - @pointerprev) else null end
set @pointerPrev = @pointer + 1
set @pointer = isnull(nullif(CHARINDEX('M',@age),0),@pointer)
set @m = case when @pointer > @pointerprev then SUBSTRING(@age,@pointerprev,@pointer - @pointerprev) else null end
set @pointerPrev = @pointer + 1
set @pointer = isnull(nullif(CHARINDEX('W',@age),0),@pointer)
set @w = case when @pointer > @pointerprev then SUBSTRING(@age,@pointerprev,@pointer - @pointerprev) else null end
set @pointerPrev = @pointer + 1
set @pointer = isnull(nullif(CHARINDEX('D',@age),0),@pointer)
set @d = case when @pointer > @pointerprev then SUBSTRING(@age,@pointerprev,@pointer - @pointerprev) else null end
set @result = dateadd(YEAR, 0 - isnull(cast(@y as int),0), @result)
set @result = dateadd(MONTH, 0 - isnull(cast(@m as int),0), @result)
set @result = dateadd(Week, 0 - isnull(cast(@w as int),0), @result)
set @result = dateadd(Day, 0 - isnull(cast(@d as int),0), @result)
return @result
end
go
select dbo.AgeToDOB( '20 Years 8 Months 3 Weeks')
注意:这里有很大的优化空间;我在上面留下了简单的内容,以帮助清楚发生了什么。