我在Microsoft SQL Server中创建了简单的表,现在我想创建"可能"容易触发。
这是我的任务:
创建或修改员工时,请填写此列 电子邮件包括:
请记住删除任何外部空格和字符 交换下划线的内部空间。
这是我用于触发器的表格:
CREATE TABLE employee
(
empID int IDENTITY(1,1) PRIMARY KEY,
surname varchar(20),
firstname varchar(20),
age int,
email varchar(100)
)
我试过这样做。这是我的版本。请检查并写下您对我的解决方案的看法:
create trigger create_email on employee
for insert,update
as
begin
declare @var_email varchar(100)
set @var_email = substring((select firstname from inserted),1,2) + '.' + substring((select surname from inserted),1,4) + '@gmail.com'
set @var_email = replace(@var_email,' ','_')
update employee set email = @var_email where empID in (select empID from inserted)
end
端
答案 0 :(得分:2)
使用计算列会更有意义:
CREATE TABLE employee
(
empID int IDENTITY(1,1) PRIMARY KEY,
surname varchar(20),
firstname varchar(20),
age int,
email as REPLACE(LTRIM(RTRIM(LEFT(firstname,2)+'.'+LEFT(surname,4)+'@gmail.com')),' ','_')
)
触发器版本为:
CREATE TRIGGER create_email ON employee
FOR INSERT, UPDATE
AS
BEGIN
UPDATE e
SET e.email = REPLACE(LTRIM(RTRIM(LEFT(i.firstname,2)+'.'+LEFT(i.surname,4)+'@gmail.com')),' ','_')
)
FROM employee e
JOIN inserted i on e.empID = i.empID
END