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 |
如何使用
如果已在数据库中创建表,则可以稍后使用此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中完成。这是一个向现有表添加多列唯一约束的示例。
在每个窗口中单击"确定",即可完成。
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 |