为什么我的CASE表达式不确定? [英] Why is my CASE expression non-deterministic?

查看:80
本文介绍了为什么我的CASE表达式不确定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用CASE表达式创建一个持久化计算列:

I am trying to create a persisted computed column using CASE expression:

ALTER TABLE dbo.Calendar ADD PreviousDate AS 
case WHEN [Date]>'20100101' THEN  [Date]
    ELSE NULL
    END PERSISTED

MSDN明确指出CASE是确定性的,此处

MSDN clearly says that CASE is deterministic, here

但是,我遇到了错误:


消息4936,级别16,状态1,第1行

表 Calendar中的 PreviousDate列无法持久保存
,因为该列是
非-确定性。

Msg 4936, Level 16, State 1, Line 1 Computed column 'PreviousDate' in table 'Calendar' cannot be persisted because the column is non-deterministic.

当然,我可以创建标量UDF并明确将其声明为确定性,但这是否有更简单的方法?我已经在获取最新的Service Pack中。谢谢。

Of course, i can create a scalar UDF and explicitly declare it as deterministic, but is there a simpler way around this? I am already in the middle of getting the latest service pack. Thanks.

推荐答案

您需要用样式转换'20100101'。


源或目标类型是datetime或
smalldatetime,其他来源或
目标类型是字符串,并指定了
a非确定性样式。

Source or target type is datetime or smalldatetime, the other source or target type is a character string, and a nondeterministic style is specified.

因此,请尝试以下操作:

So, try this:

...WHEN [Date] > CONVERT(datetime, '20100101', 112)....

从字符串中解析日期可能不可靠作为我之前已经回答过(大多在评论中)

Date parsing from string can be unreliable as I've answered before (mostly in comments)

编辑:

我不会说这是一个错误,但是SQL Server要求100%澄清。 yyyymmdd不是ISO,SQL Server解析yyyy-mm-dd不可靠(请参阅我的答案链接)

I wouldn't say it's a bug, but SQL Server asking for 100% clarification. yyyymmdd is not ISO and SQL Server parsing yyyy-mm-dd is unreliable (see my answer link)

这篇关于为什么我的CASE表达式不确定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆