Database/MS-SQL | Posted by 아키텍처 2012. 4. 24. 18:05

FunAgeRange 나이대 계산 (10대,20대..)

 
 

Create Function [dbo].[FunAgeRange](@ToYear Char(4), @BirthYY Char(2), @Range Char(1))

 Returns  VarChar(10)

As
 Begin

  Declare @AgeRange  VarChar(10)
  Declare @Age   TinyInt
  Set @AgeRange = ''
  Set @ToYear  = Convert(Int, @ToYear)
  Set @Age  = @ToYear - (1900 + Convert(Int, @BirthYY)) + 1
 
  IF @Range = '1'  -- 5세 단위
   Begin

    Select @AgeRange = 
         Case
          When @Age >= 0 And @Age <= 10 Then '10세 이하'
          When @Age >= 11 And @Age <= 15 Then '10~15세'
          When @Age >= 16 And @Age <= 20 Then '16~20세'
          When @Age >= 21 And @Age <= 25 Then '21~25세'
          When @Age >= 26 And @Age <= 30 Then '26~30세'
          When @Age >= 31 And @Age <= 35 Then '31~35세'
          When @Age >= 36 And @Age <= 40 Then '36~40세'
          When @Age >= 41 And @Age <= 45 Then '41~45세'
          When @Age >= 46 And @Age <= 50 Then '46~50세'
          When @Age >= 51 And @Age <= 55 Then '51~55세'
          When @Age >= 56 And @Age <= 60 Then '56~60세'
          When @Age >= 61 And @Age <= 65 Then '61~65세'
          When @Age >= 66 And @Age <= 70 Then '66~70세'
          When @Age >= 71 And @Age <= 75 Then '71~75세'
          When @Age >= 76 And @Age <= 80 Then '76~80세'
          When @Age >= 81 And @Age <= 85 Then '81~85세'
          When @Age >= 86 And @Age <= 90 Then '86~90세'
          When @Age >= 91 And @Age <= 95 Then '91~95세'
          When @Age >= 96 And @Age <= 100 Then '96~100세'
          When @Age >= 101    Then '100세 초과'
          Else Convert(VarChar(10), @Age)
         End

   End
  Else IF @Range = '2'  -- 10세 단위
   Begin

    Select @AgeRange = 
         Case
          When @Age >= 0 And @Age <= 10 Then '10대 이하'
          When @Age >= 11 And @Age <= 20 Then '10대'
          When @Age >= 21 And @Age <= 30 Then '20대'
          When @Age >= 31 And @Age <= 40 Then '30대'
          When @Age >= 41 And @Age <= 50 Then '40대'
          When @Age >= 51 And @Age <= 60 Then '50대'
          When @Age >= 61 And @Age <= 70 Then '60대'
          When @Age >= 71 And @Age <= 80 Then '70대'
          When @Age >= 81 And @Age <= 90 Then '80대'
          When @Age >= 91 And @Age <= 100 Then '90대'
          When @Age >= 101    Then '100세 초과'
          Else Convert(VarChar(10), @Age)
         End

   End
  Else If @Range = '3'
   Begin
    Select @AgeRange = 
         Case
          When @Age >= 0 And @Age <= 10 Then '10대 이하'
          When @Age >= 11 And @Age <= 20 Then '10대'
          When @Age >= 21 And @Age <= 30 Then '20대'
          When @Age >= 31 And @Age <= 40 Then '30대'
          When @Age >= 41 And @Age <= 50 Then '40대'
          When @Age >= 51     Then '50대이상'
          Else Convert(VarChar(10), @Age)
         End

   End
  
  Return(@AgeRange)

 End

Posted by 김준홍 (http://www.Juuun.com)