我正在寻找一种通过以下查询在字段 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。
答案 0 :(得分:1)
您遇到类型转换问题,在这种情况下,从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;