Some simple notes:
1) You should follow Mitch Wheat's advice and rewrite these triggers because inserted
and deleted
tables could have more than one row. For example, your trigger will have a bad behavior when is executed the next statement UPDATE [dbo].[alemp_persons] SET function = CASE WHEN id_person = 1 THEN 'Candidate' ELSE 'Examiner' END WHERE id_person IN (1,2)
if the first person's function is 'Examiner' and the second person's function is 'Candidate'.
2) [dbo].[alemp_persons].function
's data type should be [tiny]int
or char(1)
and not varchar(something greater than 1)
(Where function='Examiner'
).
3) [dbo].[alemp_persons].function
column should disallow Nulls.
4) [dbo].[alemp_persons].function
column should has a CHECK constraint:
ALTER TABLE [dbo].[alemp_persons] ADD CONSTRAINT CK_alemp_persons_function_Verify CHECK ( function IN ('Candidate', 'Examiner') );
5) It would be nice to add
a
function
column to[dbo].[alemp_candidates]
and[dbo].[alemp_examiners]
tables,two check constraints on
[dbo].[alemp_candidates]
(function = 'Candidate'
) and[dbo].[alemp_examiners]
(function = 'Examiner'
),an UNIQUE index on
[dbo].[alemp_persons](id_person, function)
,two FKs between
[dbo].[alemp_candidates/examiners](id_person, function)
and[dbo].[alemp_persons](id_person, function)
.
This way, you can be sure that [dbo].[alemp_candidates]
table has only candidates and [dbo].[alemp_examiners]
has only examiners and every person can be only candidate or examiner at one time.
6) You should disallow IDENTITY
property for id_person
columns in [dbo].[alemp_candidates]
and [dbo].[alemp_examiners]
table (SET IDENTITY_INSERT dbo.alemp_candidates ...
).
8) And this statement IF @newFunction = 'Candidate'
should raise an error because @newFunction
data type is 'INT'.
9) And the AFTER UPDATE
trigger on [dbo].[alemp_persons]
table will move data between candidates and examiners tables (not tested):
ALTER TRIGGER [dbo].[role_update]
ON [dbo].[alemp_persons]
FOR UPDATE
AS
BEGIN
DECLARE @selected_rows TABLE (
id_person INT PRIMARY KEY, -- or BIGINT, look at alemp_person.id_person data type
new_function VARCHAR(50) NOT NULL -- look at alemp_person.function column data type
);
INSERT @selected_rows (id_person, new_function)
SELECT new.id_person, new.function
FROM inserted as new INNER JOIN deleted as old ON new.id_person = old.id_person
WHERE new.function <> old.function;
MERGER dbo.alemp_candidates AS dest
USING @selected_rows AS src ON dest.id_person = src.id_person
WHEN MATCHED THEN
DELETE
WHEN NOT MATCHED BY TARGET AND src.new_function = 'Candidate' THEN
INSERT (id_person, random_number)
VALUES (src.id_person, CONVERT(BINARY(2), CHECKSUM(NEWID()));
MERGER dbo.alemp_examiners AS dest
USING @selected_rows AS src ON dest.id_person = src.id_person
WHEN MATCHED THEN
DELETE
WHEN NOT MATCHED BY TARGET AND src.new_function = 'Examiner' THEN
INSERT (id_person)
VALUES (src.id_person);
END