I am trying to create a persisted computed column in a SYSTEM_VERSIONING
table dbo.Users
as follows:
ALTER TABLE dbo.Users
ADD SessionId AS usr.GetSession() PERSISTED
CONSTRAINT FK_dboUsers_IdSession
FOREIGN KEY REFERENCES dbo.Sessions(IdSession)
Where usr.GetSession()
is just retrieving the value stored as BIGINT
in SESSION_CONTEXT('IdSession')
and converting it to again to BIGINT
.
CREATE OR ALTER FUNCTION usr.GetSession()
RETURNS BIGINT WITH SCHEMABINDING
AS
BEGIN
RETURN CONVERT(BIGINT, SESSION_CONTEXT(N'IdSession'))
END
But getting the following error:
Computed column 'SessionId' in table 'Users' cannot be persisted because the column is non-deterministic.
It is obviously because:
SELECT OBJECTPROPERTY(OBJECT_ID('usr.GetSession'), 'IsDeterministic') AS IsDeterministic;
Is returning 0
A little bit of searching found this about Deterministic and nondeterministic functions
CONVERT
Deterministic unless one of these conditions exists:
- Source type is sql_variant.
- Target type is sql_variant and its source type is nondeterministic.
So, I am understanding that there is no way to make my computed column persisted with a user defined scalar function as sql_variant
cannot be handled as deterministic value.
Or there can be some walk around to solve my problem? Or some other solution? Any idea?