Change empty string to NULL when column has DATE constraint

回眸只為那壹抹淺笑 提交于 2019-12-25 00:40:05

问题


This might be impossible but I was wondering if someone more experienced knew if this is possible to do in postgresql.

I have a column in my create statement

CREATE table IF NOT EXISTS (other cols, some_date DATE, other cols);

When I extract the json object from the API, there might actually be an empty string '' instead of a empty cell. Which of course gives me the following error psycopg2.errors.InvalidDatetimeFormat: invalid input syntax for type date: ""

The solution would simply to change the constraint to VARCHAR, but i was wondering if there was some way in the CREATE TABLE or INSERT statements to say the following pseudo code: if empty string insert NULL.


回答1:


Use NULLIF in your INSERT statement:

INSERT INTO your_table (cols..., some_date) VALUES (..., NULLIF(your_input_field, ''))

If you want to insert NULL if the value in question is any of a number of values, it may be easiest to use a CASE statement:

INSERT INTO your_table (cols..., some_date)
VALUES (..., CASE WHEN your_input_field IN ('', '#', '-', '--', '??') THEN NULL ELSE your_input_field END)

Could do the same with an array as well, if that's easier:

INSERT INTO your_table (cols..., some_date)
VALUES (..., CASE WHEN your_input_field = ANY('{"",#,-,--,??}'::TEXT[]) THEN NULL ELSE your_input_field END)



回答2:


Here's an example of the solution posted by 404 that checks what we are trying to insert in our db is a NITS (nothing interesting to say), and replace it with NULL.

CREATE TABLE COMPANY(
   ID             VARCHAR,
   NAME           VARCHAR,
   AGE            VARCHAR,
   ADDRESS        VARCHAR,
   DATE           INTEGER
);

INSERT INTO COMPANY (ID, NAME, AGE, ADDRESS, DATE)
VALUES (CASE WHEN cast('a' as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE 'a' END,
        CASE WHEN cast('gino' as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE 'gino' END,
        CASE WHEN cast('' as text) IN ('', '#', '-', '--', '??', 'na') THEN NULL ELSE '' END,
        CASE WHEN cast('via figa' as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE 'via figa' END,
        CASE WHEN cast(1 as text) IN ('', '#', '-', '--', '??') THEN NULL ELSE 1  END);


来源:https://stackoverflow.com/questions/56258007/change-empty-string-to-null-when-column-has-date-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!