DB2: Won't Allow “NULL” column?

邮差的信 提交于 2019-12-03 11:43:16

问题


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 null values is not allowed in DB2 altough it is totally OK in MSSQL and Oracle DBs. Technically I can change it to:

'' 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??


回答1:


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

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



回答2:


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

NULL on 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

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


来源:https://stackoverflow.com/questions/2509233/db2-wont-allow-null-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!