IF EXIST 在 PostgreSQL 中的许多插入之前存在?
IF EXIST before many insertions in PostgreSQL?
我只想在 table 存在时插入。
伪代码
IF EXISTS TABLE file_headers(
INSERT INTO file_headers
(measurement_id, file_header_index_start, file_header_index_end)
VALUES (1, 1, 100);
INSERT INTO file_headers
(measurement_id, file_header_index_start, file_header_index_end)
VALUES (1, 2, 100);
... -- many INSERTs into same table
);
如何仅在 PostgreSQL 中存在 table 时才插入?
do $$begin
if exists (select * from pg_catalog.pg_tables where tablename = 'mytable') then
insert into mytable (col1) values (1);
end if;
end$$;
如果您想将 table 名称传递给动态执行的函数,则此测试很有意义。
有一个内置的解决方案:如果你想确保 table 存在,将其转换为 regclass
(或使用一个 regclass
参数到你的函数开始)。验证存在并同时转义可能的非标准语法:
- How to check if a table exists in a given schema
- Table name as a PostgreSQL function parameter
我只想在 table 存在时插入。 伪代码
IF EXISTS TABLE file_headers(
INSERT INTO file_headers
(measurement_id, file_header_index_start, file_header_index_end)
VALUES (1, 1, 100);
INSERT INTO file_headers
(measurement_id, file_header_index_start, file_header_index_end)
VALUES (1, 2, 100);
... -- many INSERTs into same table
);
如何仅在 PostgreSQL 中存在 table 时才插入?
do $$begin
if exists (select * from pg_catalog.pg_tables where tablename = 'mytable') then
insert into mytable (col1) values (1);
end if;
end$$;
如果您想将 table 名称传递给动态执行的函数,则此测试很有意义。
有一个内置的解决方案:如果你想确保 table 存在,将其转换为 regclass
(或使用一个 regclass
参数到你的函数开始)。验证存在并同时转义可能的非标准语法:
- How to check if a table exists in a given schema
- Table name as a PostgreSQL function parameter