PostgreSQL ''空字符处理(兼容oracle)

PostgreSQL中的’‘空字符是属于字符串类型的数据,而在oracle中,’'会默认转换成NULL,所以可以使用任何数据类型。

例子:

oracle:
建表:
varchar和date类型都支持’'空字符。

SQL> create table t1(id int, c1 varchar2(10) default '', c2 date default ''); 

Table created.

SQL> insert into t1 (id) values(1);

1 row created.

查询:
查询时使用is null能够匹配相关的数据。

SQL> select * from t1 where c1 is null;

        ID C1         C2
---------- ---------- ---------
         1

SQL> select * from t1 where c2 is null;

        ID C1         C2
---------- ---------- ---------
         1

然而直接使用’'竟然查询不出结果!

SQL> select * from t1 where c1 = '';        

no rows selected

也就是说ORACLE内部把’'转换成了NULL。

PostgreSQL:
PG不做这个转换,所以非字符串类型,使用’'都会报错。

bill@bill=>create table t1(id int, c1 varchar(10) default '', c2 date default ''); 
ERROR:  invalid input syntax for type date: ""
LINE 1: ...e t1(id int, c1 varchar(10) default '', c2 date default '');

所以为了兼容oracle,在这种场景下需要将’'修改成NULL。

bill@bill=> create table a(id int, c1 varchar(10) default null, c2 timestamp(0) default null);
CREATE TABLE
bill@bill=>insert into a (id) values (1);  
INSERT 0 1

使用is null也可以匹配到相关的数据。

bill@bill=>select * from a where c1 is null;
 id | c1 | c2 
----+----+----
  1 |    | 
(1 row)


bill@bill=>select * from a where c2 is null;  
 id | c1 | c2 
----+----+----
  1 |    | 
(1 row)
发布了155 篇原创文章 · 获赞 88 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_39540651/article/details/105358848