É possível INSERT
inserir valores em uma tabela PostgreSQL a partir de uma SELECT
instrução e usar DEFAULT
valores para as colunas que são nulos?
No meu caso, a SELECT
instrução está selecionando de JSON.
Nas tentativas abaixo, obtive sucesso recuperando explicitamente a sequência, mas espero que haja uma maneira de INSERT usando os valores DEFAULT. Ou selecione valores DEFAULT sem precisar chamar explicitamente as funções padrão.
-- Example table
create table animals
(
id serial,
nm character varying (30) NOT NULL, --name
typ character varying(10),
tvi integer,
tvf numeric(8,3)
);
insert into animals VALUES (DEFAULT,'mouse','m',4,12.45);
select row_to_json(a) from animals a;
select * from json_populate_record(null::animals,'{"id":null,"nm":"mouse","typ":"m","tvi":4,"tvf":12.450}');
--All good.
-- Attempt #1
INSERT INTO animals
select id ,nm,typ,tvi,tvf from json_populate_record(null::animals,'{"id":null,"nm":"mouse","typ":"m","tvi":4,"tvf":12.450}');
/*
ERROR: null value in column "id" violates not-null constraint
DETAIL: Failing row contains (null, mouse, m, 4, 12.450).
********** Error **********
ERROR: null value in column "id" violates not-null constraint
SQL state: 23502
Detail: Failing row contains (null, mouse, m, 4, 12.450).
*/
-- Attempt #2
INSERT INTO animals
select DEFAULT,nm,typ,tvi,tvf from json_populate_record(null::animals,'{"id":null,"nm":"mouse","typ":"m","tvi":4,"tvf":12.450}');
/* I didn't expect this to work, but it does illustrate what I am trying to accomplish
ERROR: syntax error at or near "DEFAULT"
LINE 2: select DEFAULT,nm,typ,tvi,tvf from json_populate_record(null...
^
********** Error **********
ERROR: syntax error at or near "DEFAULT"
SQL state: 42601
Character: 28
*/
-- Attempt #3
INSERT INTO animals
select nextval('animals_id_seq'::regclass),nm,typ,tvi,tvf from json_populate_record(null::animals,'{"id":null,"nm":"mouse","typ":"m","tvi":4,"tvf":12.450}');
/* This works, but I'm hoping for a way to accomplish this without knowing the underlying functions generating the default values.
Query returned successfully: one row affected, 11 msec execution time.
*/
select version(); --'PostgreSQL 9.5.1, compiled by Visual C++ build 1800, 64-bit'
Se você adicionar todos os ColumnsNames (excluir a coluna 'id') após o Tablename, haverá Inserir o serial automaticamente como:
Você também pode adicionar um Valor PADRÃO em sua Coluna, para definir um Valor Padrão se a coluna não estiver na lista Inserir Coluna.
Se você deseja adicionar mais de um registro:
Isso é meio relacionado. Achei útil quando todas as colunas têm padrões.