创建触发器以为null分配值

问题描述 投票:0回答:2

我正在尝试在SSMS中创建一个触发器,如果​​新插入行的Email为null,则使用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)
);
sql tsql triggers ssms
2个回答
0
投票

您触发代码会引发各种错误:首先,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

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

Demo on DB Fiddle

insert into StudentInformation(Title, FirstName, LastName) values('Foo', 'Bar', 'Baz');
select Title, FirstName, LastName, Email from StudentInformation;
Title | FirstName | LastName | Email                                             
:-----| :---------| :--------| :----------------
Foo   | Bar       | Baz      | [email protected]                                  

0
投票

对于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
© www.soinside.com 2019 - 2024. All rights reserved.