到目前为止,我一直在使用ISNULL(dbo.fn_GetPrice(ItemId), 0),使其不能为空(而不是把它默认值,但不管)。

这是正确的方式?

有帮助吗?

解决方案

是的,这是做正确的方式。通过使用isnull功能要创建一个必须返回一个值,不管是什么表现。这是通过SQL Server的评价为一个计算的列,它是not null

其他提示

我宁愿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

和C2是确实不可为空根据的sp_help,但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)

导致违反约束。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top