简体   繁体   English

如何转换 sql_variant 使其可以被认为是确定性的

[英]How to convert sql_variant so it can be considered deterministic

I am trying to create a persisted computed column in a SYSTEM_VERSIONING table dbo.Users as follows:我正在尝试在SYSTEM_VERSIONINGdbo.Users中创建一个持久计算列,如下所示:

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 . usr.GetSession()只是在SESSION_CONTEXT('IdSession')中检索存储为BIGINT的值并将其再次转换为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.无法保留表“用户”中的计算列“会话 ID”,因为该列是不确定的。

It is obviously because:很明显是因为:

SELECT OBJECTPROPERTY(OBJECT_ID('usr.GetSession'), 'IsDeterministic') AS IsDeterministic;

Is returning 0正在返回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.源类型是 sql_variant。
  • Target type is sql_variant and its source type is nondeterministic.目标类型是 sql_variant,其源类型是不确定的。

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.所以,我知道没有办法让我的计算列与用户定义的标量 function 保持一致,因为sql_variant不能作为确定性值处理。

Or there can be some walk around to solve my problem?或者可以到处走走来解决我的问题? Or some other solution?还是其他解决方案? Any idea?任何想法?

No, there is no workaround.不,没有解决方法。 You cannot do anything with sql_variant unless you convert it (even implicitly), and as you mention, that is not deterministic.除非您转换它(甚至是隐式转换),否则您无法对sql_variant执行任何操作,并且正如您所提到的,这不是确定性的。


Be that as it may, it seems you are going down the wrong road anyway.尽管如此,你似乎还是走错了路。

A computed column is the wrong thing here , as in this case it would change every time it was read, whereas it seems you want it changed every time the row is inserted.计算列在这里是错误的,因为在这种情况下,每次读取它都会更改,而您似乎希望每次插入行时都更改它。

Instead you need a DEFAULT相反,您需要一个DEFAULT

ALTER TABLE dbo.Users 
    ADD SessionId bigint DEFAULT (usr.GetSession())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM