我有以下3个表,我试图将模式更改为[Check] .FromCompanyID,[Check] .ToCompanyID和[ActivityToCheck] .ActivityID的唯一性。除了将两个FromCompanyID和ToCompanyID添加到[ActivityToCheck]表之外,我怎样才能修改模式,以便在其中一个表上添加唯一约束?
CREATE TABLE [dbo].[Activity](
[ActivityID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NOT NULL,
[StartDate] [date] NOT NULL,
[EndDate] [date] NOT NULL,
[Description] [nvarchar](255) NULL
--<OTHER COLUMNS>
)
CREATE TABLE [dbo].[Check](
[CheckID] [int] IDENTITY(1,1) NOT NULL,
[CheckNumber] [nvarchar](255) NOT NULL,
[CheckDate] [date] NOT NULL,
[CheckDescription] [nvarchar](255) NULL,
[FromCompanyID] [int] NOT NULL,
[ToCompanyID] [int] NOT NULL
--<OTHER COLUMNS>
)
CREATE TABLE [dbo].[ActivityToCheck](
[ActivityToCheckID] [int] IDENTITY(1,1) NOT NULL,
[ActivityID] [int] NOT NULL,
[CheckID] [int] NOT NULL
)
编辑:架构绑定视图是否是确保唯一性的合理方式:
CREATE VIEW TestView
WITH SCHEMABINDING AS
SELECT ActivityToCheckID, CheckNumber, CheckID, FromCompanyID, ToCompanyID, ActivityID, AmountPaid
FROM [dbo].[Check] c
inner join [dbo].ActivityToCheck a on c.CheckID = a.CheckID
GO
CREATE UNIQUE CLUSTERED INDEX testindex on TestView (FromCompanyID, ToCompanyID, ActivityID)
GO
谢谢,
答案 0 :(得分:0)
您必须对dbo.Check
表使用以下触发器:
CREATE TRIGGER YourTriggerName ON dbo.[check]
INSTEAD OF INSERT
AS BEGIN
IF EXISTS(SELECT *
FROM Inserted i
INNER JOIN dbo.ActivityToCheck a1 ON i.CheckId = a1.CheckId
INNER JOIN dbo.ActivityToCheck a2 ON a2.ActivityId = a1.ActivityId
INNER JOIN dbo.[CHECK] c ON c.CheckId = a2.CheckId AND c.FromCompanyId=i.FromCompanyId AND c.ToCompanyId=i.ToCompanyId) BEGIN
RAISERROR('Your information is duplicate.',16,1)
RETURN;
End
INSERT INTO dbo.[check] (CheckNumber, CheckDate, CheckDescription, FROMCompanyId, ToCompanyId)
SELECT CheckNumber, CheckDate, CheckDescription, FROMCompanyId, ToCompanyId
FROM Inserted
END
如果FromCompanyId或ToCompanyId可编辑且可以更改,则必须为dbo.Check
表创建而不是更新触发器。