MS SQL Server cross table constraint

后端 未结 2 988
执笔经年
执笔经年 2020-12-17 23:11

I have three tables:

1) Applications (AppId, Name)
2) Screen (ScreenId, Name)
3) Relation (AppId, ScreenId)

Now I want to apply some restrictions on

相关标签:
2条回答
  • 2020-12-17 23:52

    It's not a great solution, but you could add triggers to screen and relation tables which just check what you've modified meets your criteria, and rollback if not.

    CREATE TRIGGER trgScreen ON Screen FOR INSERT, UPDATE
    AS
    BEGIN
        IF EXISTS (SELECT r.AppID, s.Name FROM Screen s
                   INNER JOIN Relation r ON s.ScreenID = r.ScreenID
                   GROUP BY r.AppID, s.Name
                   HAVING count(*) > 1)
            ROLLBACK TRANSACTION
    END
    
    CREATE TRIGGER trgRelation ON Relation FOR INSERT, UPDATE
    AS
    BEGIN
        IF EXISTS (SELECT r.AppID, s.Name FROM Screen s
                   INNER JOIN Relation r ON s.ScreenID = r.ScreenID
                   GROUP BY r.AppID, s.Name
                   HAVING count(*) > 1)
            ROLLBACK TRANSACTION
    END
    
    0 讨论(0)
  • 2020-12-18 00:15

    You can create an indexed view based on the Relation and Screen tables and apply a unique constraint there.

    create view DRI_UniqueScreens
    with SCHEMABINDING
    as
        select r.AppId,s.Name
        from
           [Schema].Relation r
             inner join
           [Schema].Screen s
             on
                r.ScreenId = s.ScreenId
    GO
    CREATE UNIQUE CLUSTERED INDEX IX_DRI_UniqueScreens
        on DRI_UniqueScreens (AppId,Name)
    
    0 讨论(0)
提交回复
热议问题