【问题标题】:If the age is older than 18, then save the Customer record如果年龄超过 18 岁,则保存客户记录
【发布时间】:2020-10-02 17:13:12
【问题描述】:

我想创建一个函数,它通过条目检查记录的年龄。如果年龄超过 18 岁,则保存记录。如果没有,请不要保存记录。

create function f_Over18 (@age date)
returns char (20)

as begin 
    --declare @returnOne int
    declare @date int
    set @date= year(getdate()) - year(@age)
    if (@date > 17)
        begin 
            print ('Age verified') --this is only an example but i want, that safes the record
        end
    else
        begin
            print ('Age not verified')
        end;
end;

非常感谢您的热心帮助。

【问题讨论】:

  • 获取年龄差异并不是计算某人年龄的正确方法。 2000 年 12 月 31 日出生的人在 2018 年 1 月 1 日不是 18 岁(他们是 17 岁零一天),而是 2018 - 2000 年是 18 岁。但是,这里有 100 个关于如何在 SQL Server 中计算年龄的示例,你有吗看过那些吗?
  • 感谢您的回复!我不知道如何工作和编写更好的函数。我搜索了很多,但找不到合适的。我想要的是,一列的生日数据类型应该是这个函数。如果条目(生日)超过 18 岁,则此函数允许保护记录,如果不是,则忽略它。

标签: sql sql-server date select sql-function


【解决方案1】:

问题实际上是关于如何在 SQL Server 中从出生日期计算年龄。这并不容易,因为没有内置函数,而且像 datediff() 这样的函数不能真正给出准确的结果(或者至少不能没有很多卷积)。

一种简单有效的方法是将出生日期和当前日期转换为YYYYMMDD的格式,然后将其转换为字符串,然后使用简单的算术运算,如下所示:

(convert(int, convert(char(8), getdate(), 112)) - convert(char(8), @dob, 112)) / 10000

在你的函数中:

create function f_Over18 (@dob date)
returns nvarchar (20)
as begin 
    declare @age int;
    declare @res nvarchar(20);
    set @age= 
        (convert(int, convert(char(8), getdate(), 112)) - convert(char(8), @dob, 112)) 
        / 10000;

    if (@age > 17)
        begin 
            set @res = 'Age verified';
        end
    else
        begin
            set @res = 'Age not verified';
        end;

    return concat(@res, ': ', @age);
end;

我稍微修改了原始代码,使其能够正确编译,并返回计算的日期(这样便于调试)。

现在we can test

出生日期 |资源 :--------- | :-------------------- 2000-01-01 |验证年龄:20 2002-06-11 |已验证年龄:18 2002-06-13 |年龄未验证:17 2010-01-01 |年龄未验证:10

【讨论】:

  • 非常感谢您的回答。我不能以这种方式使用用户定义的函数吗?创建表测试(first_name varchar(20),生日 f_Over18());因为,对我来说显示错误!
  • @Patrick:不,你不能那样做。即使可以,请记住,年龄确实会随着时间而变化,因此这不是您要存储的信息。无论如何,你现在问的是一个不同的问题,所以你可能应该ask a new question,清楚地了解你的需求。
猜你喜欢
  • 2010-12-21
  • 2018-05-11
  • 2022-07-01
  • 2019-03-14
  • 1970-01-01
  • 2021-12-16
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多