计算工龄,格式为n年n月n天


计算工龄函数,就是从到职日期到当前有多少年多少月多少天:

/*
功能:統計工齡,格式: n年n月n日
設計:ok_008
日期:2008-01
備注:
*/
CREATE   FUNCTION  SumWorkAge ( @OnDutyTime   datetime )
RETURNS   nvarchar ( 50 AS   
BEGIN  
    
DECLARE   @Today   datetime
    
SELECT   @Today = Today  FROM  vwgToday
RETURN     
    
CAST (( CASE   WHEN   DAY ( @OnDutyTime ) <= DAY ( @Today )   THEN   0   ELSE   - 1   END   + DATEDIFF ( Month , @OnDutyTime , @Today )) / 12   AS   nvarchar ( 2 ))  + ' '
    
+RIGHT ( ' 0 ' + CAST (( CASE   WHEN   DAY ( @OnDutyTime ) <= DAY ( @Today )   THEN   0   ELSE   - 1   END   + DATEDIFF ( Month , @OnDutyTime , @Today )) % 12   AS   nvarchar ( 2 )), 2 + ' '
    
+RIGHT ( ' 0 ' + CAST ( CASE   WHEN   DAY ( @OnDutyTime ) <= DAY ( @Today )   THEN    DAY ( @Today ) - DAY ( @OnDutyTime ELSE  
        
DATEDIFF ( Day , @OnDutyTime , DATEADD ( month , 1 , @OnDutyTime )) - DAY ( @OnDutyTime ) + DAY ( @Today END   AS   nvarchar ( 20 )), 2 + ' '
END






@OnDutyTime参数是到职日期。 vwgToday是一个取当前日期的视图(因为在自定义函数中不能直接使用GETDATE())

视图
vwgToday代码:
CREATE   VIEW  dbo.vwgToday
AS
SELECT           GETDATE ()  AS  Today







你可能感兴趣的:(计算)