What you have here appears to be an XY Problem. As has been mentioned in the comments multiple times, SQL Server has facilities to handle the creation of incrementing values by the use of IDENTITY
and SEQUENCE
. An IDENTITY
is a column property, whereas a SEQUENCE
is a database object and so can be referenced by multiple tables.
Normally, when using a SEQUENCE
you will define the use of it in a DEFAULT
CONSTRAINT
, then in a similar way to IDENTITY
you can omit the column from the INSERT
clause and SQL Server will handle the values automatically.
As we don't have a shema for your tables here, I use some simple table to demonstrate the use of both IDENTITY
and SEQUENCE
, though it seems it's the latter you want.
CREATE SEQUENCE dbo.MySequence
START WITH 1 INCREMENT BY 1;
GO
CREATE TABLE dbo.MyTable (ID int IDENTITY(1,1),
SequenceVal int NOT NULL CONSTRAINT DF_MyTableSequenceVal DEFAULT NEXT VALUE FOR dbo.MySequence,
SomeDate date NULL,
TableName AS N'MyTable');
CREATE TABLE dbo.YourTable (ID int IDENTITY(1,1),
SequenceVal int NOT NULL CONSTRAINT DF_YourTableSequenceVal DEFAULT NEXT VALUE FOR dbo.MySequence,
SomeDate date NULL,
TableName AS N'YourTable');
CREATE TABLE dbo.AnotherTable (ID int IDENTITY(1,1),
SequenceVal int NOT NULL CONSTRAINT DF_AnotherTableSequenceVal DEFAULT NEXT VALUE FOR dbo.MySequence,
SomeDate date NULL,
TableName AS N'AnotherTable');
GO
INSERT INTO dbo.MyTable
DEFAULT VALUES;
INSERT INTO dbo.MyTable (SomeDate)
VALUES(GETDATE())
INSERT INTO dbo.YourTable
DEFAULT VALUES;
INSERT INTO dbo.MyTable
DEFAULT VALUES;
INSERT INTO dbo.AnotherTable (SomeDate)
VALUES(DATEADD(DAY, -1,GETDATE()))
INSERT INTO dbo.MyTable (SomeDate)
VALUES(DATEADD(DAY, -2,GETDATE()))
GO
SELECT *
FROM dbo.MyTable
UNION ALL
SELECT *
FROM dbo.YourTable
UNION ALL
SELECT *
FROM dbo.AnotherTable
ORDER BY SequenceVal ASC;
GO
DROP TABLE dbo.MyTable;
DROP TABLE dbo.YourTable;
DROP TABLE dbo.AnotherTable;
DROP SEQUENCE dbo.MySequence;
This results in the following dataset:
ID |
SequenceVal |
SomeDate |
TableName |
1 |
1 |
NULL |
MyTable |
2 |
2 |
2023-04-13 |
MyTable |
1 |
3 |
NULL |
YourTable |
3 |
4 |
NULL |
MyTable |
1 |
5 |
2023-04-12 |
AnotherTable |
4 |
6 |
2023-04-11 |
MyTable |
Notice that the value of the identity repeats, but the SEQUENCE
is unique.