Sql Postgres:在带有“with data”的查询中使用NULLIF
我正在寻找一种方法,通过此查询为field agency_id的空字符串插入NULL: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
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,我可以重现我的问题: