SQL 练习40

  • 按照出生日期来计算学生的年龄信息
IF OBJECT_ID('GetStudentAge','FN') IS NOT NULL
	DROP FUNCTION GetStudentAge
GO
CREATE FUNCTION GetStudentAge(@birth DATE) RETURNS INT
AS
BEGIN
DECLARE @age INT

SET @age = year(GETDATE()) - YEAR(@birth)
IF MONTH(GETDATE()) < MONTH(@birth)
	set @age = @age -1
ELSE IF MONTH(GETDATE()) = MONTH(@birth) AND DAY(GETDATE()) < DAY(@birth)
	set @age = @age-1
RETURN @age
END


SELECT *,dbo.GetStudentAge(sage) 年龄 from Student

image

posted @ 2021-08-21 11:14  弩哥++  阅读(36)  评论(0编辑  收藏  举报