多列的唯一约束

时间:2010-08-13 06:04:42

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

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 studio添加唯一约束? fcode, scode, dcode必须是唯一的。

4 个答案:

答案 0 :(得分:378)

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

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

答案 1 :(得分:268)

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

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

因此,resuting表定义为:

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]

答案 2 :(得分:40)

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

  1. 在表格下方,右键点击索引 - >点击/悬停新索引 - >点击非群集索引...
  2. enter image description here

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

      1. 检查要包含的列
      2. enter image description here

        点击每个窗口中的确定,即可完成。

答案 3 :(得分: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