这有点恶心,因为它包括触发器和光标:(
它在父表中包含一个基于子表的列
设置:
CREATE TAble Parent
(
Id INT Primary Key,
Name VARCHAR(50),
ChildItems VARCHAR(200) NOT NULL UNIQUE
)
CREATE TABLE Child
(
Id INT Primary Key,
Name VARCHAR(50)
)
CREATE TABLE ParentChild
(
Id INT Identity Primary Key,
ParentId INT,
ChildId Int
)
触发器
-- This gives the unique colmn a default based upon the id of the parent
CREATE TRIGGER trg_Parent ON Parent
INSTEAD OF Insert
AS
SET NOCOUNT ON
INSERT INTO Parent (Id, Name, ChildItems)
SELECT Id, Name, '/' + CAST(Id As Varchar(10)) + '/'
FROM Inserted
GO
-- This updates the parent with a path based upon child items
-- If a the exact same child items exist for another parent then this fails
-- because of the unique index
CREATE Trigger trg_ParentChild ON ParentChild
AFTER Insert, Update
AS
DECLARE @ParentId INT = 0
DECLARE @ChildItems VARCHAR(8000) = ''
DECLARE parentCursor CURSOR FOR
SELECT DISTINCT ParentId
FROM Inserted
OPEN parentCursor
FETCH NEXT FROM parentCursor INTO @ParentId
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @ChildItems = COALESCE(@ChildItems + '/ ', '') + CAST(ChildID As Varchar(10))
FROM ParentChild
WHERE ParentId = @ParentId
ORDER BY ChildId
UPDATE Parent
SET ChildItems = @ChildITems
WHERE Id = @ParentId
FETCH NEXT FROM parentCursor INTO @ParentId
SET @ChildItems = ''
END
CLOSE parentCursor
DEALLOCATE parentCursor
GO
数据设置
INSERT INTO Parent (Id, Name)
VALUES (1, 'Parent1'), (2,'Parent2'), (3, 'Parent3')
INSERT INTO Child (Id, Name)
VALUES (1,'Child1'), (2,'Child2'), (3,'Child3'), (4,'Child4')
现在插入一些数据
-- This one succeeds
INSERT INTO ParentChild (ParentId, ChildId)
VALUES (1,1),(1,2),(2,2),(2,3)
-- This one Fails
INSERT INTO ParentChild (ParentId, ChildId) VALUES (3,1),(3,2)