简体   繁体   English

如何在视图的计算列中强制执行NOT NULL

[英]How to enforce NOT NULL in a view's computed column

I want to alter a view as follows: 我想改变一个视图如下:

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

Since columnOne is "not null" I want to force columnThree to be "not null" also. 由于columnOne是“not null”,我想强制columnThree也“非null”。 Is is possible, impossible, implicit, useless or could cause serious problems since columnOne is char(2) populated with algarisms only. 是可能的,不可能的,隐含的,无用的,或者可能导致严重的问题,因为columnOne只是char(2)填充了algarisms。

I simply would like to know the syntax 我只是想知道语法

You can use ISNULL() to ensure a default value when null. 您可以使用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 

如果column1被约束为NOT NULL,则column3不能为NULL,因此无需担心它。

ColumnThree will never be null if the source of the Cast is itself never null. 如果Cast的源本身永远不为null,ColumnThree将永远不会为null。 However, that does not mean you will not get an exception if ColumnOne cannot be cast to decimal(2,0) and you will not know whether you will get an exception until you query against the view. 但是,这并不意味着如果ColumnOne无法转换为decimal(2,0) ,您将不会获得异常,并且在查询视图之前您不会知道是否会获得异常。 You should consider adding an additional check to determine whether the cast will fail and help mitigate the possibility of a cast error: 您应该考虑添加一个额外的检查来确定转换是否会失败并帮助减少强制转换错误的可能性:

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

How you enforce it depends on your business rules. 您如何执行它取决于您的业务规则。

Do you want those rows to not show up in the view results? 您希望这些行不显示在视图结果中吗? Then add that criteria to the view WHERE clause. 然后将该条件添加到视图WHERE子句中。

Do you want to use a default value if the column would be NULL? 如果列为NULL,是否要使用默认值? Then use COALESCE to return your default value for NULLs (just remember to alias the column). 然后使用COALESCE返回NULL的默认值(只需记住别名列)。

Do you want an error returned if a row is inserted into the underlying table(s) that would cause such a thing? 如果将一行插入到可能导致此类事情的基础表中,您是否希望返回错误? In that case I would put the constraint on the underlying table(s). 在这种情况下,我会将约束放在基础表上。 If your view includes JOINs and aggregates then that might be difficult, but without a specific example I can't really help on that. 如果您的视图包含JOIN和聚合,那么这可能很困难,但是如果没有特定示例,我就无法提供帮助。

In any case, for your specific example you shouldn't see any NULL values since columnOne is NOT NULL. 在任何情况下,对于您的特定示例,您不应该看到任何NULL值,因为columnOne是NOT NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM