So, I’m trying to create a trigger that will throw an error on inserting data if a foreign key code is not valid. I have two tables, Publisher and Title. Title has a publisher code on it, as does Publisher. I have the trigger on my Title for insert, and I am currently doing an if not exists and selecting the Publisher row where the code is equal to the inserted row’s publisher code. I don’t know if this is the right way to do it, and probably not, as SQL is giving me a “multi-part identifier Inserted.PublisherCode could not be found” error. Any help you guys could give would be appreciated. Thanks.
go
create trigger TR_Title_PublisherCode_Insert
on title
for Insert
as
if not exists(select * from Publisher where PublisherCode = Inserted.PublisherCode)
begin
raiserror('Publisher does not exist', 16, 1)
rollback tran
end
INSERTED and DELETED are table too
So you have to do this:
By the way, as hkf said, if you identified PublisherCode AS foreign key, you won’t have a need to make trigger