Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql Postgres:在带有“with data”的查询中使用NULLIF_Sql_Postgresql - Fatal编程技术网

Sql Postgres:在带有“with data”的查询中使用NULLIF

Sql Postgres:在带有“with data”的查询中使用NULLIF,sql,postgresql,Sql,Postgresql,我正在寻找一种方法,通过此查询为field agency_id的空字符串插入NULL: WITH data(email, agency_id, address, city, zipcode) AS ( VALUES ('email@domain.tld', '', 'My Address', 'My City', 'My Zipcode') ) INSERT INTO customers (email, agency_id) SELECT email, NULLIF(agency_id

我正在寻找一种方法,通过此查询为field agency_id的空字符串插入NULL:

WITH data(email, agency_id, address, city, zipcode) AS (
    VALUES ('email@domain.tld', '', 'My Address', 'My City', 'My Zipcode')
)

INSERT INTO customers (email, agency_id)
SELECT email, NULLIF(agency_id, '') FROM data
在这个查询中,代理id必须为NULL,但用这种方式它不起作用。
我想在某个地方使用NULLIF。

您有一个类型转换问题,在本例中是从VARCHAR到INT。如果您的表是:

CREATE TABLE customers (
    email text NOT NULL,
    agency_id integer NULL
);
您需要转换:

将该值设置为null。 文本形式的数值,如'123'varchar到123 int。 以下查询将起作用:

WITH data(email, agency_id, address, city, zipcode) AS (
    VALUES ('email@domain.tld', '', 'My Address', 'My City', 'My Zipcode')
)
INSERT INTO customers (email, agency_id)
SELECT email, 
  case when agency_id = '' then null
       else agency_id::int
  end 
FROM data;

这对我很有用:你的具体问题是什么?使用integer,我可以重现我的问题: