带有附加列值检查的SQL外键约束

时间:2016-08-01 09:35:11

标签: sql sql-server sql-server-2008

我有这种情况

CREATE TABLE [dbo].[Customer]
(
    Id INT IDENTITY(1,1) NOT NULL,
    IsWholesaler BIT NOT NULL,
    Name NVARCHAR(255) NOT NULL
)

CREATE TABLE [dbo].[WholesalerUser]
(
    Id INT IDENTITY(1,1) NOT NULL,
    CustomerId INT NOT NULL,
    UserId INT NOT NULL
)

CREATE TABLE [dbo].[User]
(
        Id INT IDENTITY(1,1) NOT NULL,
        Name NVARCHAR(255)
)

将IsWholesaler列设置为true的一个客户可以拥有多个用户。 我为此目的使用WholesalerUser表,但外键WholesalerUser.CustomerId已附加到Customer.Id,但如何检查列IsWholesaler = 1

1 个答案:

答案 0 :(得分:0)

可以同时在多个列上定义外键。

  • IsWholesaler列添加到WholesalerUser
  • 添加检查约束以确保它始终为1
  • 在两列(CustomerId, IsWholesaler)上定义外键。
  • 要定义此类外键,Customer表应包含(ID, IsWholesaler)主键或(ID, IsWholesaler)上的单独唯一索引。

Customer

CREATE TABLE [dbo].[Customer](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [IsWholesaler] [bit] NOT NULL,
    [Name] [nvarchar](255) NOT NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
))

支持外键约束的唯一索引:

CREATE UNIQUE NONCLUSTERED INDEX [IX_ID_IsWholesaler] ON [dbo].[Customer] 
(
    [Id] ASC,
    [IsWholesaler] ASC
)

WholesalerUser

CREATE TABLE [dbo].[WholesalerUser](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [CustomerId] [int] NOT NULL,
    [IsWholesaler] [bit] NOT NULL,
    [UserId] [int] NOT NULL,
CONSTRAINT [PK_WholesalerUser] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
))

外键

ALTER TABLE [dbo].[WholesalerUser] WITH CHECK 
ADD CONSTRAINT [FK_WholesalerUser_Customer] 
FOREIGN KEY([CustomerId], [IsWholesaler])
REFERENCES [dbo].[Customer] ([Id], [IsWholesaler])
GO

ALTER TABLE [dbo].[WholesalerUser] 
CHECK CONSTRAINT [FK_WholesalerUser_Customer]
GO

检查约束

ALTER TABLE [dbo].[WholesalerUser] WITH CHECK 
ADD CONSTRAINT [CK_WholesalerUser] 
CHECK (([IsWholesaler]=(1)))
GO

ALTER TABLE [dbo].[WholesalerUser] 
CHECK CONSTRAINT [CK_WholesalerUser]
GO

ALTER TABLE [dbo].[WholesalerUser] 
ADD CONSTRAINT [DF_WholesalerUser_IsWholesaler] 
DEFAULT ((1)) FOR [IsWholesaler]
GO