创建触发器以为null分配值

时间:2019-03-12 22:16:54

标签: sql tsql triggers ssms

我正在尝试在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)
);

1 个答案:

答案 0 :(得分: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