--drop table #tmp
--go
--create table #tmp(id int,xm varchar(10),nl varchar(10),sfz varchar(19),csrq datetime)
--insert into #tmp(id,xm,nl,sfz,csrq) values(3,'张三','','440106197805015047','1978-05-01')
--insert into #tmp(id,xm,nl,sfz,csrq) values(4,'李四','','440106198005045047','1980-05-04')
--insert into #tmp(id,xm,nl,sfz,csrq) values(5,'王五','','','1980-05-04')
--insert into #tmp(id,xm,nl,sfz,csrq) values(6,'赵六','','440106200008102451',null)
--insert into #tmp(id,xm,nl,sfz,csrq) values(7,'刘七','','440106200008102451','')
select * from #tmp
--身份证为字符串,年龄为字符串,出生日期为日期
--利于身份证来计算年龄
select id,xm,
cast(datediff(yyyy,cast((case when len(sfz)>=15 then substring(sfz,7,4)+'-'+ substring(sfz,11,2)+'-'+substring(sfz,13,2) else null end) as datetime),getdate()) as varchar)+'岁' as nl,
csrq from #tmp
--出生日期来计算年龄
select id,xm,
cast(datediff(yyyy,case when year(csrq)<=1900 then null else csrq end,getdate()) as varchar)+'岁' as nl,
csrq from #tmp
图片附件: 游客没有浏览图片的权限,请
登录 或
注册