多列的唯一约束

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, dcodet-sql和/或management studio fcode, scode, dcodefcode, scode, dcode必须是唯一的。

通过在表创build上使用约束定义,您可以指定跨越多个列的一个或多个约束。 从technet的文档简化的语法forms是:

 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] 

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

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

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

  1. 在表格下,右键单击索引 – >单击/hover新索引 – >单击非聚集索引…

在这里输入图像说明

  1. 将会给出一个默认的索引名称,但您可能想要更改它。 选中唯一checkbox,然后单击添加…button

在这里输入图像说明

  1. 检查你想包括的列

在这里输入图像说明

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

 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