zoukankan      html  css  js  c++  java
  • t-sql计算年龄

    不多说,直接开整。

    测试表:

    CREATE TABLE [dbo].[staff](
    	[id] [varchar](50) NOT NULL,
    	[birthdate] [datetime] NULL,
    	[age] [int] NULL,
     CONSTRAINT [PK_staff] PRIMARY KEY CLUSTERED 
    (
    	[id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    

      数据自己加,上存储过程

    create proc hr_autochange_age
    as
    BEGIN
    	set nocount on 
    	declare age_cur cursor for
    		select id,isnull(birthdate,'') from Staff
    	open age_cur
    	declare @id varchar(255)
    	declare @birthday datetime
    	fetch age_cur into @id,@birthday
    	while @@fetch_status=0
    	begin
    		IF(@birthday IS NOT NULL AND ISDATE(@birthday) = 1)
    			BEGIN
    				DECLARE @age INT , @y INT , @m INT , @d INT , @now DATETIME
    				SET @now = GETDATE()
    				SET @y = DATEPART(YEAR,@now) - DATEPART(YEAR,@birthday)
    				SET @m = DATEPART(MONTH,@now) - DATEPART(MONTH,@birthday)
    				SET @d = DATEPART(DAY,@now) - DATEPART(DAY,@birthday)
    				IF(@m = 0 AND @d = 0)
    					BEGIN
    						SET @age = @y
    					END
    				ELSE
    					BEGIN
    						IF @m > 0 OR (@m = 0 AND @d > 0)
    							SET @age = @y
    						ELSE
    							SET @age = @y - 1
    					END
    				IF @age < 0 
    					SET @age = 0
    			END
    		ELSE
    			BEGIN
    				SET @age = NULL
    			END
    		update Staff set age=@age where id=@id
    		fetch age_cur into @id,@birthday 
    	end
    	close age_cur
    	deallocate age_cur
    	set nocount off 
    END
    

      好,完事。

    **********初心不改,方得始终。
  • 相关阅读:
    python命令行参数处理
    linux进程管理
    hadoop
    linux进程间通信之信号
    HA for openstack
    ubutun 安装php7.1x
    php 函数小技巧(一)
    git error: RPC failed; result=56, HTTP code = 200
    php面试题汇总四(基础篇附答案)
    php面试题汇总三(基础篇附答案)
  • 原文地址:https://www.cnblogs.com/salv/p/10492181.html
Copyright © 2011-2022 走看看