关于sql server:多列的唯一约束

Unique constraint on multiple columns

1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE TABLE [dbo].[user](
        [userID] [int] IDENTITY(1,1) NOT NULL,
        [fcode] [int] NULL,
        [scode] [int] NULL,
        [dcode] [int] NULL,
        [name] [nvarchar](50) NULL,
        [address] [nvarchar](50) NULL,
     CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED
    (
        [userID] ASC
    )
    ) ON [PRIMARY]

    GO

如何使用t-sql和/或management studio为列fcode, scode, dcode添加唯一约束? fcode, scode, dcode必须是唯一的。


如果已在数据库中创建表,则可以稍后使用此SQL查询添加唯一约束:

1
2
ALTER TABLE dbo.User
  ADD CONSTRAINT ucCodes UNIQUE (fcode, scode, dcode)


通过在表创建上使用约束定义,您可以指定跨越多个列的一个或多个约束。从technet文档中简化的语法采用以下形式:

1
2
3
4
CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ]
(
    column [ ASC | DESC ] [ ,...n ]
)

因此,resuting表的定义是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
CREATE TABLE [dbo].[user](
    [userID] [int] IDENTITY(1,1) NOT NULL,
    [fcode] [int] NULL,
    [scode] [int] NULL,
    [dcode] [int] NULL,
    [name] [nvarchar](50) NULL,
    [address] [nvarchar](50) NULL,
    CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED
    (
        [userID] ASC
    ),
    CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
    (
        [fcode], [scode], [dcode]
    )
) ON [PRIMARY]


这也可以在GUI中完成。这是一个向现有表添加多列唯一约束的示例。

  • 在表格下方,右键单击索引 - >单击/悬停新索引 - >单击非聚集索引...
  • enter image description here

  • 将给出默认的索引名称,但您可能想要更改它。选中唯一复选框,然后单击添加...按钮
  • enter image description here

  • 检查要包含的列
  • enter image description here

    在每个窗口中单击"确定",即可完成。


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    USE [TSQL2012]
    GO

    /****** Object:  Table [dbo].[Table_1]    Script Date: 11/22/2015 12:45:47 PM ******/
    SET ANSI_NULLS ON
    GO

    SET QUOTED_IDENTIFIER ON
    GO

    CREATE TABLE [dbo].[Table_1](
        [seq] [bigint] IDENTITY(1,1) NOT NULL,
        [ID] [int] NOT NULL,
        [name] [nvarchar](50) NULL,
        [cat] [nvarchar](50) NULL,
     CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
    (
        [ID] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
     CONSTRAINT [IX_Table_1] UNIQUE NONCLUSTERED
    (
        [name] ASC,
        [cat] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]

    GO