不多说,直接开整。
测试表:
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
好,完事。