I'm trying to create the following logic in a SQL Server trigger:
I tried:
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
is a table (pseudo-table) and as such could have multiple rows - some of which may have ProfID = 3
and some of which may have ProfId <> 3
. This must be handled. Also relational databases are designed for set based operations, not procedural ones. Your logic can be built into a single insert statement with the appropriate where
clause. The following reproduces what you have shown above:
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
);