多列的唯一约束


248
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

如何为fcode, scode, dcode带有t-sql和/或的列添加唯一约束management studiofcode, scode, dcode在一起必须唯一。


9
这是否意味着您可以拥有许多相同的fcode或scode或dcode,但不能有两个记录具有相同的fcode和scode AND dcode?
Jimbo,2010年

Answers:


291

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

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

因此,重新表定义将是:

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]

418

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

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

还是ADD CONSTRAINT ucCodes UNIQUE NONCLUSTERED
Kiquenet '16

52

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

  1. 在表格下,右键单击索引 ->单击/悬停新索引 ->单击非聚集索引...

在此处输入图片说明

  1. 将提供默认的索引名称,但您可能需要更改它。选中唯一复选框,然后单击添加...按钮

在此处输入图片说明

  1. 检查您要包含的列

在此处输入图片说明

在每个窗口中单击“ 确定”,就完成了。


1
注意:如果您已经在设计视图中打开表,则此选项不可用。因此,请先关闭设计标签,然后再进行操作。
musefan '19

0
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

13
尽管此代码可以回答问题,但最好包含一些上下文,说明其工作方式和使用时间。从长远来看,纯代码答案没有用。
波诺2015年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.