SQL通過日期計算年齡


首先建立一個表如下:

=======================

BirthDay  datetime not null

Age    通過公式計算得出

=======================

以上是表的兩個字段,通過BirthDay字段的數據自動生成Age字段

Age字段的公式如下:

(case when (datediff(year,[BirthDay],getdate()) <> 0) then (ltrim(datediff(year,[BirthDay],getdate())) + '歲') else (case when (datediff(month,[BirthDay],getdate()) <> 0) then (ltrim(datediff(month,[BirthDay],getdate())) + '月') else (case when (datediff(day,[BirthDay],getdate()) <> 0) then (ltrim(datediff(day,[BirthDay],getdate())) + '天') else '' end) end) end)

這樣子產生的數據就是通過填寫的日期計算的。

下面是一個簡單的SQL語句:

 1 SELECT  * ,
 2         ( CASE WHEN ( DATEDIFF(year, [BirthDay], GETDATE()) <> 0 )
 3                THEN ( LTRIM(DATEDIFF(year, [BirthDay], GETDATE())) + '' )
 4                ELSE ( CASE WHEN ( DATEDIFF(month, [BirthDay], GETDATE()) <> 0 )
 5                            THEN ( LTRIM(DATEDIFF(month, [BirthDay], GETDATE()))
 6                                   + '' )
 7                            ELSE ( CASE WHEN ( DATEDIFF(day, [BirthDay],
 8                                                        GETDATE()) <> 0 )
 9                                        THEN ( LTRIM(DATEDIFF(day, [BirthDay],
10                                                              GETDATE())) + '' )
11                                        ELSE ''
12                                   END )
13                       END )
14           END )
15 FROM    Test

以上是進行測試的代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM