I need to share a single SQL Server sequence between tables in two different SQL Server databases. This example works just fine for two existing tables and a sequence defined on the same database:
USE DatabaseA ;
GO
CREATE SEQUENCE dbo.TransactionSequence START WITH 1 INCREMENT BY 1 ;
GO
ALTER TABLE Table1 ADD TransactionSequenceID int NOT NULL
CONSTRAINT DF_Table1_TransactionSequence DEFAULT (NEXT VALUE FOR dbo.TransactionSequence) ;
ALTER TABLE Table2 ADD TransactionSequenceID int NOT NULL
CONSTRAINT DF_Table2_TransactionSequence DEFAULT (NEXT VALUE FOR dbo.TransactionSequence) ;
GO
However, this command fails for a table in a different database:
USE DatabaseB ;
GO
ALTER TABLE Table3 ADD TransactionSequenceID int NOT NULL
CONSTRAINT DF_Table3_TransactionSequence DEFAULT (NEXT VALUE FOR DatabaseA.dbo.TransactionSequence) ;
GO
It fails because SQL Server does not allow a DEFAULT constraint to reference a sequence in another database.
A sequence cannot be referenced indirectly through a synonym in this context, and NEXT VALUE FOR <sequence>
is not allowed inside of a function or several other possibly-useful constructs. Is it possible for tables in different databases to share a single sequence? If so, then how?