如何使计算列不可为空?
到目前为止,我一直在使用 ISNULL(dbo.fn_GetPrice(ItemId), 0) 使其不可为空(而不是称其为默认值,但无论如何)。
这是正确的方法吗?
So far I've been using ISNULL(dbo.fn_GetPrice(ItemId), 0)
to make it not nullable (rather call it default-valued, but whatever).
Is this the right way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是正确的做法。通过使用
isnull
函数,您将创建一个无论如何都必须返回值的表达式。 SQL Server 将其评估为not null
的计算列。Yes, that is the right way to do it. By using the
isnull
function you are creating an expression that must return a value, no matter what. This is evaluated by SQL Server to be a computed column that isnot null
.我更喜欢 ANSI 标准 COALESCE 函数,但 ISNULL 也可以。要使用 COALESCE,请将计算列定义为:
编辑 每天学习新东西。我执行了以下操作:
根据 sp_help,c2 确实不可为空,但 c4 被报告为可为空,即使合并表达式不可能导致空值。
另外,截至 2008 年,我不知道 2005 年是否存在该选项,可以保留计算列并添加约束:
导致违反约束。
I'd prefer the ANSI standard COALESCE function, but ISNULL is fine. To use COALESCE, define your computed column as:
EDIT Learn something new everyday. I did the following:
And c2 is indeed not nullable according to sp_help, but c4 is reported as being nullable, even though there is no way that coalesce expression could result in a null value.
Also as of 2008, I don't know whether the option exists in 2005, one can persist a computed column and add a constraint:
results in a constraint violation.