【问题标题】:Create Trigger for assigning value for null创建用于为 null 赋值的触发器
【发布时间】:2019-03-12 22:16:54
【问题描述】:

我正在尝试在 SSMS 中创建一个触发器,如果​​新插入的行的电子邮件为空,则使用 FirstName + LastName + '@gmail.com' 添加电子邮件

这是我目前所拥有的,但它看起来绝对不正确:

Drop Trigger if exists trg_assignEmail
Go
Create Trigger 
    trg_assignEmail 
On StudentInformation
For Insert 
As
Begin
    Insert Into StudentInformation
    Set Email = Null
    Select rtrim(FirstName + LastName) + '@gmail.com'
    From StudentInformation
Where Email is Null

架构:

Create Table StudentInformation (
    StudentID int not null identity (100,1),
    Title nchar(50) null, 
    FirstName nchar (50) null,
    LastName nchar (50) null,
    Address1 nchar (50) null,
    Address2 nchar (50) null,
    City nchar (50) null, 
    County nchar (50) null,
    Zip nchar (10) null, 
    Country nchar (50) null,
    Telephone nchar (50) null,
    Email nchar (50) null, 
    Enrolled nchar (50) null,
    AltTelephone nchar(50) null
    Constraint PK_StudentID Primary Key (StudentID)
);

【问题讨论】:

  • 每次插入表格时都在创建表格,正常吗?不要忘记在触发器声明的末尾写 END。
  • 为什么要花时间写一个问题但实际测试它?

标签: sql tsql triggers ssms


【解决方案1】:

您的触发器代码引发了各种错误:首先,INSERT ... SET ... FROM ... 不是有效的 SQL 语法。

我认为与您的用例相关的方法是创建一个AFTER INSERT 触发器,它将检查刚刚插入的值(使用伪表inserted),并在需要时更新Email .

CREATE TRIGGER trg_assignEmail ON StudentInformation
AFTER INSERT
As
BEGIN
    UPDATE s
    SET s.Email = TRIM(i.FirstName) + TRIM(i.LastName) + '@gmail.com'
    FROM StudentInformation s
    INNER JOIN inserted i ON i.StudentID = s.StudentID AND i.email IS NULL
END

inserted 上的INNER JOIN 用于选择刚刚插入的记录,如果没有给出Email

Demo on DB Fiddle

insert into StudentInformation(Title, FirstName, LastName) values('Foo', 'Bar', 'Baz');
select Title, FirstName, LastName, Email from StudentInformation;
标题 |名字 |姓氏 |电子邮件 :-----| :---------| :--------| :---------------- 福 |酒吧 |巴兹 | BarBaz@gmail.com

【讨论】:

    【解决方案2】:

    对于 2017 年之前的版本,请尝试。并不是说trim() 不能替换为 rtrim() 或 ltrim() 并且还可以处理空字符串(在使用表单保存时与应用程序常见)

    Create Trigger 
        trg_assignEmail 
    On StudentInformation
    For Insert 
    As
    Begin
        declare @email as nchar(50)
            ,@id int
        select @email = Email, @id = StudentID from inserted
        if nullif(@email,'') is null 
            begin
                update StudentInformation
                set Email = rtrim(FirstName + LastName) + '@gmail.com'
                where StudentID = @id
            end
    end
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 2014-12-04
      • 1970-01-01
      • 2012-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多