1

我有一个有 10 列的表,但只关心 3 列。想象一下我的桌子是这样的:

CREATE TABLE MyTable ( RowID int IDENTITY(1,1), UserID int, NodeID int, RoleID int )

我需要的是一个强制执行以下内容的约束:对于每个 NodeID,UserID 和 RoleID 需要是唯一的(即,用户不能在多个节点中具有相同的角色)。换句话说,我想允许

INSERT MyTable (UserID, NodeID, RoleID) SELECT 1, 1, 1

但不允许

INSERT MyTable (UserID, NodeID, RoleID) SELECT 1, 2, 1

如果第一次插入已经发生,因为这将导致用户在多个节点中具有角色。

希望这很简单,我只是让它比我大脑中需要的更复杂。

4

2 回答 2

2

由于您的约束取决于其他行中的数据,因此排除了过滤索引。IMO 一个可行的选择可能是一个触发器。这样的触发器可能看起来像这样:

CREATE TRIGGER dbo.MyTrigger ON dbo.Q1
    AFTER INSERT, UPDATE
AS
    DECLARE @userId INT, @Id INT, @roleId INT, @exists INT;

    SELECT TOP 1
            @userId = userID
           ,@roleId = roleID
           ,@Id = Id
    FROM    inserted;    

    SELECT TOP 1
            @exists = Id
    FROM    Q1
    WHERE   userId = @userId
            AND roleID = @roleID AND Id<> @Id;    

    IF ISNULL(@exists, 0) > 0 
        BEGIN           
            -- you would want to either undo the action here when you use an 'after' trigger
            -- because as the name implies ... the after means the record is allready inserted/updated          
            RAISERROR ('No way we would allow this.', 16, 1);
        END
        -- else
        -- begin
            -- another alternative would be to use a instead of trigger, which means the record
            -- has not been inserted or updated and since that type of trigger runs the trigger 'instead of'
            -- updating or inserting the record you would need to do that yourself. Pick your poison ...
        -- end
GO
于 2013-05-30T05:17:16.267 回答
1

唯一索引应该强制执行您的要求

CREATE UNIQUE NONCLUSTERED INDEX [idx_Unique] ON [dbo].[MyTable] 
(
    [UserID] ASC,
    [NodeID] ASC,
    [RoleID] ASC
)

从评论中我想你需要两个唯一的索引

CREATE UNIQUE NONCLUSTERED INDEX [idx_User_Node] ON [dbo].[MyTable] 
(
    [UserID] ASC,
    [NodeID] ASC
)
GO
CREATE UNIQUE NONCLUSTERED INDEX [idx_User_Role] ON [dbo].[MyTable] 
(
    [UserID] ASC,
    [RoleID] ASC
)
于 2013-05-29T22:08:04.683 回答