我这个函数是取得身份证(18位)的出生日期,不知为什么出错?

xjb_netboy 2004-10-14 09:31:21
我这个函数是取得身份证(18位)的出生日期,不知为什么出错?
CREATE FUNCTION GetIDBirthDate (@id15 char(18))
RETURNS char(8) AS
BEGIN
(
DECLARE @Age as char(8)
Select @Age=SUBSTRING(@id15,7,8)
RETURN @Age
)
END

还有我想把他直接转成smalldatetime (yyyy-mm-dd)类型.
...全文
171 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
kejian 2004-12-08
  • 打赏
  • 举报
回复
为什么全都没有做容错处理??
tinghuyang 2004-10-18
  • 打赏
  • 举报
回复
up
mastersky 2004-10-14
  • 打赏
  • 举报
回复
15位、18位都可以处理


CREATE FUNCTION GetIDBirthDate (@id15 varchar(18))
RETURNS smalldatetime AS
BEGIN
declare @age char(10)

if Len(@id15)=15
begin
set @age=substring(@id15,7,6)
set @age=substring(@age,3,2)+'/'+substring(@age,5,2)+'/19'+substring(@age,1,4)
end
else if Len(@id15)=18
begin
set @age=substring(@id15,7,8)
set @age=substring(@age,5,2)+'/'+substring(@age,7,2)+'/'+substring(@age,1,4)
end
return convert(datetime,@age)
END

select [dbo].[GetIDBirthDate]('232143198011191055')

结果:
1980-11-19 00:00:00

select [dbo].[GetIDBirthDate]('232143801119055')

结果:
1980-11-19 00:00:00

mastersky 2004-10-14
  • 打赏
  • 举报
回复
CREATE FUNCTION GetIDBirthDate (@id15 char(18))
RETURNS smalldatetime AS
BEGIN

declare @age char(10)

set @age=substring(@id15,7,8)

set @age=substring(@age,5,2)+'/'+substring(@age,7,2)+'/'+substring(@age,1,4)

return convert(datetime,@age)

END

select [dbo].[GetIDBirthDate]('232143198011191055')

结果:
1980-11-19 00:00:00

zjcxc 2004-10-14
  • 打赏
  • 举报
回复
--同意 pbsql

CREATE FUNCTION GetIDBirthDate (@id15 char(18))
RETURNS smalldatetime AS --这里直接修改返回类型就可以解决楼主的类型转换问题了
BEGIN
DECLARE @Age as char(8)
Select @Age=case when len(@id15)=18 then SUBSTRING(@id15,7,8)
when SUBSTRING(@id15,7,2)>'50' then '19'+SUBSTRING(@id15,7,6)
else '18'+SUBSTRING(@id15,7,6) end
RETURN @Age
END
victorycyz 2004-10-14
  • 打赏
  • 举报
回复
CREATE FUNCTION GetBirthDay (@dt char(18))
RETURNS smalldatetime
AS
BEGIN

DECLARE @birthday smalldatetime
Select @birthday=cast(SUBSTRING(@dt,7,8) as smalldatetime)
RETURN @birthday

END
go
pbsql 2004-10-14
  • 打赏
  • 举报
回复
要考虑15位、18位,处理方式不同的:
CREATE FUNCTION GetIDBirthDate (@id15 char(18))
RETURNS char(8) AS
BEGIN
DECLARE @Age as char(8)
Select @Age=case when len(@id15)=18 then SUBSTRING(@id15,7,8)
when SUBSTRING(@id15,7,2)>'50' then '19'+SUBSTRING(@id15,7,6)
else '18'+SUBSTRING(@id15,7,6) end
RETURN @Age
END

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧