2

我想改变一个视图如下:

ALTER VIEW [dbo].[ViewOne] as  
SELECT columnOne,  -- not null  
       columnTwo, --not null
      (convert(decimal(2,0), columnOne)) as columnThree -- I want this not to be NULL
FROM DBOne.TableOne

由于 columnOne 是“not null”,我想强制 columnThree 也为“not null”。是可能的、不可能的、隐含的、无用的或可能导致严重问题,因为 columnOne 是 char(2) 仅填充了 algarisms。

我只是想知道语法

4

4 回答 4

4

您可以ISNULL()在 null 时使用来确保默认值。

ALTER VIEW [dbo].[ViewOne] as   
SELECT columnOne,  -- not null   
       columnTwo, --not null 
      ISNULL((convert(decimal(2,0), columnOne)),0.00) as columnThree
FROM DBOne.TableOne 
于 2010-08-04T15:18:58.537 回答
4

如果 column1 被限制为 NOT NULL,则 column3 不能为 NULL,因此无需担心。

于 2010-08-04T15:23:42.730 回答
4

如果 Cast 的源本身从不为空,则 ColumnThree 将永远不会为空。但是,这并不意味着如果无法强制转换 ColumnOne 就不会出现异常,decimal(2,0)并且在查询视图之前您不会知道是否会出现异常。您应该考虑添加一个额外的检查来确定转换是否会失败并帮助减少转换错误的可能性:

Alter View dbo.ViewOne
As
Select ColumnOne, ColumnTwo
    , Case
        When IsNumeric( ColumnOne ) = 0 Then 0
        Else Cast( ColumnOne As decimal(2,0) )
        End As ColumnThree
于 2010-08-04T15:37:54.440 回答
0

您如何执行它取决于您的业务规则。

您是否希望这些行不显示在视图结果中?然后将该条件添加到视图 WHERE 子句中。

如果列为 NULL,是否要使用默认值?然后使用 COALESCE 返回 NULL 的默认值(只需记住为列命名)。

如果将一行插入会导致此类事情的基础表中,您是否希望返回错误?在这种情况下,我会将约束放在基础表上。如果您的视图包含 JOIN 和聚合,那么这可能会很困难,但如果没有具体的示例,我对此无能为力。

无论如何,对于您的具体示例,您不应该看到任何 NULL 值,因为 columnOne 不是 NULL。

于 2010-08-04T15:31:43.427 回答