CREATE FUNCTION [dbo].[GetAllocatedStartTime](@Year INT,@Week INT) RETURNS DATETIME WITH schemabinding AS BEGIN RETURN dateadd(week,@Week-(1),dateadd(day,(-1),dateadd(week,datediff(week,(0),CONVERT([varchar](4),@Year,(0))+'-01-01'),(1)))) END GO
我添加了WITH模式绑定,希望它会使它确定性,所以我可以坚持下去.应该是作为两个输入[周]和[年]将总是产生相同的结果.@H_502_5@
Computed column ‘AllocatedTimeStart’ in table ‘Tmp_Bookings’ cannot be persisted because the column is non-deterministic.@H_502_5@
我在列中使用这个公式:@H_502_5@
([dbo].[GetAllocatedStartTime]([Year],[Week]))
列清除:@H_502_5@
[Week] [int] NOT NULL,[Year] [int] NOT NULL,[AllocatedTimeStart] AS ([dbo].[GetAllocatedStartTime]([Year],[Week])),
有任何想法吗?@H_502_5@
编辑:@H_502_5@
改为:@H_502_5@
RETURN dateadd(week,CONVERT(datetime,(0))+'0101',112)),(1))))
但是现在我收到一个错误,表示该列的公式无效.即使功能很好.@H_502_5@
编辑2:@H_502_5@
我已经显示了我正在做的(或至少我已经尝试过).没有什么额外的真的正如它之前的功能(原来的一个)加上公式ref [dbo] .AllocatedStartDate(…)在列中的工作,但不是坚持,它说这是非确定性的.所以根据建议我改变了FUNCTION,用新的代码替换了转换部分,所以这个功能现在看起来像:@H_502_5@
FUNCTION [dbo].[GetSTime](@Year INT,@Week INT) RETURNS DATETIME WITH schemabinding AS BEGIN RETURN dateadd(week,(1)))) END
然后我在计算的字段(([dbo].[GetAllocatedStartTime]([Year],[Week])))中尝试了与之前相同的公式,并拒绝该公式,表示其无效…这是奇怪的是,公式是一样的,所以它必须做一些检查更改的函数,并发现无效,这也是奇怪的,因为我做了一个简单的SELECT dbo.GetAllocatedStartTime(2012,13),它的工作. ..@H_502_5@
所以是的,我很困惑,我从来没有看过sqlFiddle从来不介意使用它.但真的没有什么比我刚刚说的更多.@H_502_5@
解决方法
从deterministic functions的规则:@H_502_5@
CAST
@H_502_5@Deterministic unless used with
datetime
,smalldatetime
,orsql_variant
.@H_502_5@
CONVERT
@H_502_5@Deterministic unless one of these conditions exists:@H_502_5@
…@H_502_5@
Source or target type is
datetime
orsmalldatetime
,the other source or target type is a character string,and a nondeterministic style is specified. To be deterministic,the style parameter must be a constant. Additionally,styles less than or equal to 100 are nondeterministic,except for styles 20 and 21. Styles greater than 100 are deterministic,except for styles 106,107,109 and 113.@H_502_5@
嗯,你既不打电话,但你依赖于一个隐含的转换,我期望像CAST一样行事.而不是依赖于此,我将切换到使用CONVERT并给出确定性样式参数.@H_502_5@
所以,我会做:CONVERT(datetime,(0))’0101′,112).这样做后,函数本身就变成了确定性的@H_502_5@