Привет, IT-сообщество. Помогите разобраться с правильным созданием триггеров в этих двух задачах:
- Триггер не позволяющий удалять диски группы The Beatles
Я попытался написать, но оно не работает вообще. Ничего не удаляется, если диск не попадает в условия. Перепробовал почти все, но никак. Может это как то связано с внешним ключом?
create trigger tg_beatles_delete_taboo on Discs
instead of delete
as
begin
declare @id int
select @id=SingerId from inserted
if exists(select SingerId from Discs d
join Singers s on s.Id=d.SingerId
where SingerId=@id and s.Name=N'The Beatles')
begin
print ('Sorry, you can not delete discs of this group')
rollback transaction
end
else
begin
delete from Discs
where exists (select SingerId from Discs d
join Singers s on s.Id=d.SingerId
where SingerId=@id)
end
end
И вторая задача для другой бд
- При удалении информации о покупателе триггер переносит
его историю покупок в таблицу «История покупок»
Тут вылетает ошибка, связанная со ссылочным ограничением
create trigger tg_purchase_history on Clients
instead of delete
as
begin
insert into PurchaseHistory(EmpId,ClientId,Product,Price,SDate)
select EmpId,ClientId,Product,Price,SDate
from SaleOfGoods sg join deleted d
on d.Id=sg.ClientId
delete from Clients
where Id in (select Id from deleted)
end