-- Creating table 'SP_Read'
CREATE TABLE [dbo].[SP_Read] (
    [TargetID] nvarchar(440)  NOT NULL,
    [PrincipalID] int  NOT NULL,
    [Timestamp] datetimeoffset  NOT NULL
);
GO

-- Creating table 'SP_ReadPrincipal'
CREATE TABLE [dbo].[SP_ReadPrincipal] (
    [SP_Read_TargetID] nvarchar(440)  NOT NULL,
    [SP_Read_PrincipalID] int  NOT NULL,
    [Principal_PrincipalID] int  NOT NULL
);
GO

-- Creating primary key on [TargetID], [PrincipalID] in table 'SP_Read'
ALTER TABLE [dbo].[SP_Read]
ADD CONSTRAINT [PK_SP_Read]
    PRIMARY KEY CLUSTERED ([TargetID], [PrincipalID] ASC);
GO


-- Creating primary key on [SP_Read_TargetID], [SP_Read_PrincipalID], [Principal_PrincipalID] in table 'SP_ReadPrincipal'
ALTER TABLE [dbo].[SP_ReadPrincipal]
ADD CONSTRAINT [PK_SP_ReadPrincipal]
    PRIMARY KEY CLUSTERED ([SP_Read_TargetID], [SP_Read_PrincipalID], [Principal_PrincipalID] ASC);
GO


-- Creating foreign key on [SP_Read_TargetID], [SP_Read_PrincipalID] in table 'SP_ReadPrincipal'
ALTER TABLE [dbo].[SP_ReadPrincipal]
ADD CONSTRAINT [FK_SP_ReadPrincipal_SP_Read]
    FOREIGN KEY ([SP_Read_TargetID], [SP_Read_PrincipalID])
    REFERENCES [dbo].[SP_Read]
        ([TargetID], [PrincipalID])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

-- Creating foreign key on [Principal_PrincipalID] in table 'SP_ReadPrincipal'
ALTER TABLE [dbo].[SP_ReadPrincipal]
ADD CONSTRAINT [FK_SP_ReadPrincipal_Principal]
    FOREIGN KEY ([Principal_PrincipalID])
    REFERENCES [dbo].[Principal]
        ([PrincipalID])
    ON DELETE NO ACTION ON UPDATE NO ACTION;
GO

-- Creating non-clustered index for FOREIGN KEY 'FK_SP_ReadPrincipal_Principal'
CREATE INDEX [IX_FK_SP_ReadPrincipal_Principal]
ON [dbo].[SP_ReadPrincipal]
    ([Principal_PrincipalID]);
GO
