CREATE TRIGGER AlbumRoleInsert ON AlbumRole INSTEAD OF INSERT AS
BEGIN
DECLARE @ALB INT, @PRF INT, @ROL VARCHAR(500), @mas INT, @pla BIT, @mem BIT, @gue BIT
DECLARE @ID INT, @RLR VARCHAR(500)
DECLARE LISTROLE CURSOR LOCAL FAST_FORWARD FOR
SELECT Album, Master, Performer, Play, Member, Role, SpecialGuest
FROM Inserted
OPEN LISTROLE
FETCH LISTROLE INTO @ALB, @mas, @PRF, @pla, @mem, @ROL, @gue
WHILE @@FETCH_STATUS = 0 BEGIN
-- Есть запись?
IF EXISTS( SELECT * FROM AlbumRole WHERE (Album = @ALB) AND (Performer = @PRF)) BEGIN
SELECT @ID = ID, @RLR = Role FROM AlbumRole WHERE (Album = @ALB) AND (Performer = @PRF)
-- Есть роль?
IF ( CHARINDEX( @ROL, @RLR) = 0 ) SET @RLR = @RLR + ', ' + @ROL
IF ( @RLR IS NULL ) SET @RLR = @ROL
-- Обновление списка.
UPDATE AlbumRole SET Role = @RLR WHERE ID = @ID
END ELSE BEGIN
-- Добавление:
INSERT INTO AlbumRole ( Album, Master, Performer, Play, Member, Role, SpecialGuest )
VALUES( @ALB, @mas, @PRF, @pla, @mem, @ROL, @gue )
END
-- Следующее поле
FETCH LISTROLE INTO @ALB, @mas, @PRF, @pla, @mem, @ROL, @gue
END
CLOSE LISTROLE
DEALLOCATE LISTROLE
END
--
GO