1

到目前为止,我一直在使用ISNULL(dbo.fn_GetPrice(ItemId), 0)它来使它不可为空(而是称它为默认值,但无论如何)。

这是正确的方法吗?

4

2 回答 2

3

是的,这是正确的做法。通过使用该isnull函数,您正在创建一个无论如何都必须返回值的表达式。这由 SQL Server 评估为计算列,即not null.

于 2009-12-21T04:25:20.927 回答
2

我更喜欢 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)

导致违反约束。

于 2009-12-21T23:15:58.297 回答