How can I create a SQL unique constraint based on 2 columns?

前端 未结 5 1416
心在旅途
心在旅途 2020-12-08 01:45

I have a Table like this one:

|UserId   |  ContactID |  ContactName 
---------------------------------------
| 12456   |  Ax759     |  Joe Smith
| 12456   |          


        
相关标签:
5条回答
  • 2020-12-08 02:19

    You can try this:

    CREATE UNIQUE CLUSTERED INDEX index_name ON TABLE (col1,col2)
    or
    CREATE UNIQUE NONCLUSTERED INDEX index_name ON TABLE (col1,col2)
    

    or

    ALTER TABLE [dbo].[TABLE] ADD CONSTRAINT
    UNIQUE_Table UNIQUE CLUSTERED
    (
    col1,
    col2
    ) ON [PRIMARY]
    
    0 讨论(0)
  • 2020-12-08 02:30

    You can try ALTER TABLE [TABLE_NAME] ADD UNIQUE (column1,column2,column3 ...columnN).

    Hope this helps cheers.

    0 讨论(0)
  • 2020-12-08 02:33

    You can add unique constraint tou your fields:

    ALTER TABLE YourTable
    ADD CONSTRAINT UQ_UserId_ContactID UNIQUE(UserId, ContactID)
    
    0 讨论(0)
  • 2020-12-08 02:34
    CREATE TABLE [LineItems](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [OrderID] [int] NOT NULL,
        [LineItemNumber] [int] NOT NULL,
     CONSTRAINT [PK_LineItems] PRIMARY KEY CLUSTERED 
    (
        [ID] ASC
    ),
     CONSTRAINT [UC_LineItems] UNIQUE NONCLUSTERED 
    (
        [OrderID] ASC,
        [LineItemNumber] ASC
    )
    )
    
    0 讨论(0)
  • 2020-12-08 02:36

    Here is the syntax for creating a unique CONSTRAINT as opposed to a unique INDEX.

    ALTER TABLE publishers 
      ADD CONSTRAINT uqc_pub_name 
      UNIQUE (pub_name)
    

    It is important to note that there are subtle differences dependent on which method you use to enfore the uniqueness of a column.

    See the following MSDN reference for an interesting walkthrough of these:

    http://msdn.microsoft.com/en-us/library/aa224827(SQL.80).aspx

    0 讨论(0)
提交回复
热议问题