如何使计算列不可为空?

发布于 2024-08-15 17:13:36 字数 97 浏览 10 评论 0原文

到目前为止,我一直在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅暮の光 2024-08-22 17:13:36

是的,这是正确的做法。通过使用 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 is not null.

冷心人i 2024-08-22 17:13:36

我更喜欢 ANSI 标准 COALESCE 函数,但 ISNULL 也可以。要使用 COALESCE,请将计算列定义为:

COALESCE(dbo.fn_GetPrice(ItemId), 0)

编辑 每天学习新东西。我执行了以下操作:

create table t (c1 int null
    , c2 as isnull(c1, 1) 
    , c3 as isnull(c1, null)
    , c4 as coalesce(c1, 1)
    , c5 as coalesce(c1, null)
    )

exec sp_help t

根据 sp_help,c2 确实不可为空,但 c4 被报告为可为空,即使合并表达式不可能导致空值。

另外,截至 2008 年,我不知道 2005 年是否存在该选项,可以保留计算列并添加约束:

create table t (c1 int null
    , c2 as isnull(c1, 1) persisted not null
    , c3 as isnull(c1, null) persisted not null
    , c4 as coalesce(c1, 1) persisted not null
    , c5 as coalesce(c1, null) persisted not null
    )
go
insert into t (c1) values (null)

导致违反约束。

I'd prefer the ANSI standard COALESCE function, but ISNULL is fine. To use COALESCE, define your computed column as:

COALESCE(dbo.fn_GetPrice(ItemId), 0)

EDIT Learn something new everyday. I did the following:

create table t (c1 int null
    , c2 as isnull(c1, 1) 
    , c3 as isnull(c1, null)
    , c4 as coalesce(c1, 1)
    , c5 as coalesce(c1, null)
    )

exec sp_help t

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:

create table t (c1 int null
    , c2 as isnull(c1, 1) persisted not null
    , c3 as isnull(c1, null) persisted not null
    , c4 as coalesce(c1, 1) persisted not null
    , c5 as coalesce(c1, null) persisted not null
    )
go
insert into t (c1) values (null)

results in a constraint violation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文