sql – 在SSMS中为常量CHAR(1)创建非NULL计算列

在我的数据库中,我有一些计算列来帮助确保参照完整性约束.我使用计算列而不是默认值列,因为我使用的LINQ2SQL不理解数据库中的默认值.

我的尝试是使用

CAST('C' as CHAR(1))

它会自动转换为

(CONVERT([char](1),'C',0))

通过SSMS.但是,这会导致NULL-able CHAR(1)列类型.

如果我只使用’C’或ISNULL(NULL,’C’)(这会导致非NULL类型),则该列将被选为VARCHAR(?).而且,如果我将两者组合使用ISNULL(NULL,CONVERT([char](1),’C’,0)),我又回到了一个可以使用NULL的CHAR(1).

我想要这个有两个原因:

>计算列将参与与外来CHAR(1)列的关系.
>非NULL CHAR(1)直接映射到LINQ2SQL中的.NET字符类型.

更新:

它适用于ISNULL(CONVERT([char](1),’C’,0),0),但我不确定“为什么”.如果有的话,似乎ISNULL(..,0)将进一步统一类型.

如果有一个很好的解释,我会非常高兴得到答案.

最佳答案 1)在SQL Server中,没有Nprefix的字符串文字始终被视为varchar(x),其中x是从字符串的长度派生的.

 +---------------+--------------+
| String Length |  Data Type   |
+---------------+--------------+
| 0             | varchar(1)   |
| 1-8000        | varchar(x)   |
| > 8000        | varchar(max) |
+---------------+--------------+

2)如Computed Columns中所述

The Database Engine automatically determines the nullability of
computed columns based on the expressions used. The result of most
expressions is considered nullable even if only nonnullable columns
are present, … An expression that is nullable can be turned into a
nonnullable one by specifying ISNULL(check_expression, constant),
where the constant is a nonnull value substituted for any null result.

3)ISNULL ( check_expression , replacement_value )的文件

Return Types Returns the same type as check_expression. If a literal
NULL is provided as check_expression, returns the datatype of the
replacement_value.

这三条信息解释了您问题中的所有行为.

点赞