逻辑如果有人出生在21世纪的SQL服务器上

时间:2014-04-02 14:20:22

标签: sql sql-server sql-server-2008 tsql

我已经建立了一个计算年龄的函数,根据瑞典ssn格式为650101-1234,我得到的所有个人ID都是10个数字。到目前为止,在我的函数中,它确实计算了年龄,但仅适用于出生的人from 1900 to 1999我将如何添加可能性来计算2000 and forward

出生的人的年龄

这是我的功能代码。

ALTER function [dbo].[Function_AGE] 
(
     @IdNr varchar(13)

) 
     returns int
     as

begin

  Declare @Calc int 

  Set @IdNr = (Select Case when LEN(@IdNr) > 11 
  then cast(left(@IdNr, 8) as date)
  else cast('19'+left(@IdNr,6) as date) end) 

  set @Calc = (select datediff(year,@IdNr,getdate())) 

Return @Calc
end  

2 个答案:

答案 0 :(得分:2)

如果前两位数字介于00和14之间,而第七位的字符不是“加号”,那么这个人就是在1999年之后出生的。所以你可以添加if-then-else逻辑来测试它。 / p>

这是一个关于如何确定括号的不太经过验证的示例,它远非完美,仅用作提示 - 它可能包含错误:)

declare @people table (pnr char(11))
insert @people values ('121212-1212'),('121212+1212'),('991212-1212')

select pnr, 
    case 
        when substring(pnr,7,1)='-' 
            and left(pnr, 2) between 00 and left(year(getdate()), 2) 
            then 'young (after 2000)' 
        when substring(pnr,7,1)='+' 
            and left(pnr, 2) between 00 and left(year(getdate()), 2) 
            then 'old 100+ (before 1914)' 
        when substring(pnr,7,1)='-' 
            and not left(pnr, 2) between 00 and left(year(getdate()), 2) 
            then 'normal (between 1914 and 1999)' 
    end as [Age span]
from @people

Result:
pnr         Age span
----------- ------------------------------
121212-1212 young (after 2000)
121212+1212 old 100+ (before 1914)
991212-1212 normal (between 1914 and 1999)

答案 1 :(得分:0)

这是我的答案,我已经对它进行了测试,它完美无缺!感谢您提供的技巧,一路上帮助了我。非常感激。

ALTER function [dbo].[AGE_Function] 
(
@IdNr varchar(13)

) 
returns int
as

begin
If SUBSTRING(@IdNr,1,2) between '20'+'00' and DATEPART(YY,GETDATE()) 
     and LEFT(@IdNr,7) =   '-'
  Begin

   Declare @Calc int 

   Set @IdNr = (Select Case when LEN(@IdNr) > 11 
   then cast(left(@IdNr, 8) as date)
   else cast('20'+left(@IdNr,6) as date) end) 

   set @Calc = (select datediff(year,@IdNr,getdate())) 
end

Else
Begin
   Set @IdNr = (Select Case when LEN(@IdNr) > 11 
   then cast(left(@IdNr, 8) as date)
   else cast('19'+left(@IdNr,6) as date) end) 

   set @Calc = (select datediff(year,@IdNr,getdate())) 
end    
   Return @Calc
end