Marcel
Marcel

Reputation: 15740

SQL: How to have a non-unique "identity column", with automatic SET behaviour?

The idea

So, the title may seem somewhat vague but this is what I would like to have (in Microsoft SQL Server, recent version), to be used from an ASP.NET C# application:

The additional "logical idendity" column should have the following properties

The last point is probably the hardest to achieve, so that's the question:

The question

How to enforce (preferably on the database level) that a mandatory value is always set to a yet unique value, when not provided by the INSERT script?

The thoughts

What I have considered yet:

The context

Upvotes: 1

Views: 1069

Answers (1)

Dan Guzman
Dan Guzman

Reputation: 46415

One option is with a SEQUENCE value assigned with a DEFAULT constraint. The immutable requirement is the biggest challenge because SQL Server doesn't provide a declarative way to specify a read-only column so one needs a trigger implementation.

Below is example DDL. I don't know if this technique will pose challenges with EF.

CREATE SEQUENCE SQ_Example_Sequence
    AS int START WITH 1 INCREMENT BY 1;
GO
CREATE TABLE dbo.Example(
     IdentityColumn int NOT NULL IDENTITY
        CONSTRAINT PK_Example PRIMARY KEY CLUSTERED
    ,SomeDataColumn int
    ,SequenceColumn int NOT NULL 
        CONSTRAINT DF_Example_SequenceColumn DEFAULT NEXT VALUE FOR SQ_Example_Sequence
);
GO
CREATE TRIGGER TR_Example_Update
    ON dbo.Example FOR UPDATE 
AS
IF EXISTS(SELECT 1
    FROM inserted
    JOIN deleted ON inserted.IdentityColumn = deleted.IdentityColumn
    WHERE inserted.SequenceColumn <> deleted.SequenceColumn
    )
BEGIN
    THROW 50000, 'SequenceColumn value cannot be changed', 16;
END;
GO

Upvotes: 2

Related Questions