Friday, 20 March 2026

SEQUENCE in a computed column or view in SQL Server

We cannot use SEQUENCE in computed columns or views because NEXT VALUE FOR is nondeterministic and state-changing. Computed columns and views must remain declarative and stable, but sequence generation can execute multiple times due to recompilation, indexing, optimization, or repeated execution, which would cause unintended number consumption and inconsistent data. Therefore, SQL Server explicitly blocks it to prevent unpredictable behavior.

Let’s see the demo

Creating sequence

CREATE SEQUENCE TestSeq_ViewDemo

START WITH 1

INCREMENT BY 1;

Now creating a table in this table, we are using this sequence as computed table

Computed column

CREATE TABLE Computed_Demo

(

    ID INT,

    SeqCol AS NEXT VALUE FOR TestSeq_ViewDemo

);

 

We can say that we can not use sequence on computed column, function, view, UDT, derive column and sub-query etc. Computed column evaluation could happen multiple times (recalculations, index rebuild, query rewrites, replication sync, etc.) SQL Server cannot risk generating unintended sequence increments.

Sequence with View

Let’s create View with sequence.

CREATE VIEW v_Test

AS

SELECT NEXT VALUE FOR TestSeq_ViewDemo

AS TestSeq_ViewDemo;

We are not able to create view. We are getting the same error as above.

A view may be executed repeatedly by multiple queries, optimizer rewrites it, may materialize it,
So SQL Server prohibits any non-declarative behavior.

 

No comments:

Post a Comment

If you have any doubt, please let me know.

Popular Posts