Postgres:在查询中使用NULLIF和“ WITH data”

时间:2019-01-11 16:55:06

标签: sql postgresql

我正在寻找一种通过以下查询在字段 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

在此查询中, agency_id 必须为NULL,但这种方式不起作用。 我想在某个地方使用NULLIF。

1 个答案:

答案 0 :(得分:1)

您遇到类型转换问题,在这种情况下,从VARCHARINT。如果您的表是:

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;
相关问题