SQL can I have a “conditionally unique” constraint on a table?

后端 未结 5 739
时光说笑
时光说笑 2020-12-17 18:03

I\'ve had this come up a couple times in my career, and none of my local peers seems to be able to answer it. Say I have a table that has a \"Description\" field which is a

5条回答
  •  粉色の甜心
    2020-12-17 18:21

    In the case of descriptions which are not yet completed, I wouldn't have those in the same table as the finalized descriptions. The final table would then have a unique index or primary key on the description.

    In the case of the active/inactive, again I might have separate tables as you did with an "archive" or "history" table, but another possible way to do it in MS SQL Server at least is through the use of an indexed view:

    CREATE TABLE Test_Conditionally_Unique
    (
        my_id   INT NOT NULL,
        active  BIT NOT NULL DEFAULT 0
    )
    GO
    CREATE VIEW dbo.Test_Conditionally_Unique_View
    WITH SCHEMABINDING
    AS
        SELECT
            my_id
        FROM
            dbo.Test_Conditionally_Unique
        WHERE
            active = 1
    GO
    CREATE UNIQUE CLUSTERED INDEX IDX1 ON Test_Conditionally_Unique_View (my_id)
    GO
    
    INSERT INTO dbo.Test_Conditionally_Unique (my_id, active)
    VALUES (1, 0)
    INSERT INTO dbo.Test_Conditionally_Unique (my_id, active)
    VALUES (1, 0)
    INSERT INTO dbo.Test_Conditionally_Unique (my_id, active)
    VALUES (1, 0)
    INSERT INTO dbo.Test_Conditionally_Unique (my_id, active)
    VALUES (1, 1)
    INSERT INTO dbo.Test_Conditionally_Unique (my_id, active)
    VALUES (2, 0)
    INSERT INTO dbo.Test_Conditionally_Unique (my_id, active)
    VALUES (2, 1)
    INSERT INTO dbo.Test_Conditionally_Unique (my_id, active)
    VALUES (2, 1)    -- This insert will fail
    

    You could use this same method for the NULL/Valued descriptions as well.

提交回复
热议问题