我正在尝试在SQL Server触发器中创建以下逻辑:
我尝试过:
IF (deleted.idsProf = 3)
BEGIN
IF NOT Exists(Select PL.idsNumber FROM tblPartLic PL INNER JOIN Deleted D
ON PL.idsNumber=D.idsNumber
WHERE PL.idsProfession = 3 AND PL.idsState <> 70)
BEGIN
INSERT INTO tblPartLic (idsNumber, txtLicNumber, txtState, txtProfOrg,
idsCountry, idsState, idsProf)
SELECT Deleted.idsDASNumber, 'AR NL', 'NL', 'Architect', 208, 70, 3
FROM Deleted
END;
END;
Deleted
是一个表(伪表),因此可以具有多个行-其中一些可能具有ProfID = 3
,而其中一些可能具有ProfId <> 3
。必须对此进行处理。关系数据库也设计用于基于集合的操作,而不是用于过程操作。您的逻辑可以使用适当的where
子句内置到单个插入语句中。以下内容重现了上面显示的内容:
INSERT INTO tblPartLic (idsNumber, txtLicNumber, txtState, txtProfOrg, idsCountry, idsState, idsProf)
SELECT D.idsDASNumber, 'AR NL', 'NL', 'Architect', 208, 70, 3
FROM Deleted D
-- Condition 1 - ProfID = 3
WHERE D.ProfID = 3
-- Condition 2 - No existing record in tblPartLic
AND NOT EXISTS (
SELECT PL.idsNumber
FROM tblPartLic PL
WHERE PL.idsProfession = 3 AND PL.idsState <> 70
AND PL.idsNumber = D.idsNumber
);