我需要帮助创建一个before insert触发器,因为我是TSQL的新手。下面是两个表格。
SALARY表:
CREATE TABLE SALARY
(
StarName varchar(30) NOT NULL,
MovieTitle varchar(30)NOT NULL,
MovieYearMade numeric(4, 0) NOT NULL,
Amount numeric(8, 0) NULL,
PRIMARY KEY (MovieTitle,StarName,MovieYearMade),
)
MOVIESTAR表
CREATE TABLE MOVIESTAR
(
Name varchar(30) NOT NULL,
Address varchar(20),
City varchar(15) DEFAULT ('Palm Springs'),
Gender char(1) NULL CHECK (Gender ='M' OR GENDER ='F'),
BirthYear Numeric(4),
PRIMARY KEY CLUSTERED (Name)
)
我想在添加新电影时创建一个触发器。如果SALARY.Amount
在SALARY.MovieYearMade
之前,则会阻止添加MOVIESTAR.BirthYear
。
当我比较两个表中的值,即SALARY
和MOVIESTAR
时,我很困惑如何定义触发器。
谢谢,
答案 0 :(得分:1)
你在找这样的东西吗?
CREATE TRIGGER tg_salary ON salary
INSTEAD OF INSERT AS
BEGIN
INSERT INTO salary (StarName, MovieTitle, MovieYearMade, Amount)
SELECT i.StarName, i.MovieTitle, i.MovieYearMade,
CASE WHEN i.MovieYearMade < s.BirthYear THEN NULL ELSE i.Amount END
FROM INSERTED i JOIN moviestar s
ON i.StarName = s.Name
END
这是 SQLFiddle 演示