Unique key vs. unique index on SQL Server 2008

前端 未结 7 1512
抹茶落季
抹茶落季 2021-02-01 00:59

I have a table called countries and I define the country_name column to be unique by creating a “Index/Key” of type “Unique Key” on SQL Server 2008 R2.

7条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 01:16

    A 3rd Option to enforce Uniqueness is using a Filtered Unique-Index to allow a Nullable Unique Index.
    This will not work with Unique-Constraints.
    For example, say you have a column where you only want to allow unique values,
       but still want to support multiple NULL values when they do not exist.
    Only a Filtered Unique-Index would work:

    CREATE UNIQUE NONCLUSTERED INDEX [UF_Employee_UserID] ON [dbo].[Employee]
    (
        [UserID] ASC--Not all Employees have a UserID to log into the System.
    )
    WHERE ([UserID] IS NOT NULL)--Enforce Uniqueness when not null.
    

    Right now, you still cannot create a Filtered-Index in SSMS while editing a Table using the GUI.
    However, you can close all of your open Table Designers, then open up the Properties of the Index itself in the Object Explorer, if you wanted to go through the GUI instead of creating the Index by hand (like above).

提交回复
热议问题