Unique constraint on multiple columns

前端 未结 4 1340
南笙
南笙 2020-11-28 01:05
CREATE TABLE [dbo].[user](
        [userID] [int] IDENTITY(1,1) NOT NULL,
        [fcode] [int] NULL,
        [scode] [int] NULL,
        [dcode] [int] NULL,
                


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 01:31

    By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:

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

    Therefore, the resuting table definition would be:

    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]
    

提交回复
热议问题