SQL DB2:不允许“NULL”列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2509233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 05:47:24  来源:igfitidea点击:

DB2: Won't Allow "NULL" column?

sqldb2

提问by GyRo

Part of a complex query that our app is running contains the lines: ...(inner query)

我们的应用程序正在运行的复杂查询的一部分包含以下行:...(内部查询)

SELECT
...
NULL as column_A,
NULL as column_B,
...
FROM
...

This syntax of creating columns with nullvalues is not allowed in DB2 altough it is totally OK in MSSQLand OracleDBs. Technically I can change it to:

这种创建值列的语法在 DB2 中是不允许的,尽管它在MSSQLOracleDB 中完全可以。从技术上讲,我可以将其更改为:

'' as column_A,
'' as column_B, 

But this doesn't have exactly the same meaning and can damage our calculation results. How can I create columns with null values in DB2 using other syntax??

但这并不具有完全相同的含义,并且会破坏我们的计算结果。如何使用其他语法在 DB2 中创建具有空值的列?

回答by Ian Bjorhovde

DB2 is strongly typed, so you need to tell DB2 what kind of column your NULL is:

DB2 是强类型的,因此您需要告诉 DB2 您的 NULL 是哪种列:

select 
   ...
   cast(NULL as int) as column_A,
   cast(NULL as varchar(128)) as column_B,
   ...
FROM
   ...

回答by Paul Vernon

For Db2 LUW, since version 9.7, you can (if you like) use the NULLvalue without explicitly casting it to a particular data type.

对于 Db2 LUW,从 9.7 版开始,您可以(如果愿意)使用该NULL值,而无需将其显式转换为特定数据类型。

NULLon it's own will be implicitly cast to VARCHAR(1). This knowledge center page will show what happens in other cases: Determining data types of untyped expressions

NULL它自己将被隐式转换为VARCHAR(1). 此知识中心页面将显示在其他情况下会发生什么: 确定无类型表达式的数据类型

Examples

例子

db2 "describe values ( NULL, + NULL, NULL || NULL  )"

 Column Information

 Number of columns: 3

 SQL type              Type length  Column name                     Name length
 --------------------  -----------  ------------------------------  -----------
 449   VARCHAR                   1  1                                         1
 997   DECFLOAT                 16  2                                         1
 449   VARCHAR                 508  3                                         1

and

db2 "describe values NULL, 1"

 Column Information

 Number of columns: 1

 SQL type              Type length  Column name                     Name length
 --------------------  -----------  ------------------------------  -----------
 497   INTEGER                   4  1                                         1