如何从年龄编号获得出生日期

时间:2016-09-12 06:18:13

标签: sql sql-server tsql

--My Age format will be like '056Yrs03Mths13Days/Male'

DECLARE @INPUT VARCHAR(250),@DATE_OF_BIRTH DATETIME,
@YEARS BIGINT , @MONTHS  BIGINT ,@DAYS BIGINT 


set @INPUT='056Yrs03Mths13Days/Male' --My INPUT age format will be like this.

SET @YEARS=CONVERT(BIGINT,SUBSTRING(@AGE_NME,1,3))
--select @YEARS

SET @MONTHS=CONVERT(BIGINT,SUBSTRING(@AGE_NME,CHARINDEX ('M',@AGE_NME,1)-2,2))
--SELECT @MONTHS

SET @DAYS=CONVERT(BIGINT,SUBSTRING(@AGE_NME,CHARINDEX ('D',@AGE_NME,1)-2,2))
--SELECT @DAYS


SET @DATE_OF_BIRTH= ?

3 个答案:

答案 0 :(得分:3)

使用DateAdd

SET @DATE_OF_BIRTH=DATEADD(year, -@Years, 
                           DATEADD(month, -@Months, 
                           DATEADD(day, -@Days, getDate())))

答案 1 :(得分:1)

两个DATEADD就足够了:

DECLARE @DATE_OF_BIRTH date 
    = DATEADD(year, -@Years, DATEADD(month, -@Months, GETDATE()))-@days

答案 2 :(得分:0)

SET @YEARS=CONVERT(BIGINT,SUBSTRING( @INPUT,1,3))

SET @MONTHS=CONVERT(BIGINT,SUBSTRING( @INPUT,CHARINDEX ('M', @INPUT,1)-2,2))

SET @DAYS=CONVERT(BIGINT,SUBSTRING( @INPUT,CHARINDEX ('D', @INPUT,1)-2,2))

SET @DATE_OF_BIRTH=DATEADD(year, -@Years,
DATEADD(month, -@Months,DATEADD(day, -@Days, getDate())))
SELECT Convert(nvarchar(12),@DATE_OF_BIRTH,105)