gpt4 book ai didi

sql - 检查表在运行时是否为空

转载 作者:行者123 更新时间:2023-11-29 11:43:13 24 4
gpt4 key购买 nike

我正在尝试编写一个脚本来删除 Postgres 数据库中的一些过时表。我想确保表在删除之前是空的。我还希望脚本可以保存在我们的迁移脚本中,即使在实际删除这些表后也可以安全运行。

这是我的脚本:

CREATE OR REPLACE FUNCTION __execute(TEXT) RETURNS VOID AS $$
BEGIN EXECUTE $1; END;
$$ LANGUAGE plpgsql STRICT;

CREATE OR REPLACE FUNCTION __table_exists(TEXT, TEXT) RETURNS bool as $$
SELECT exists(SELECT 1 FROM information_schema.tables WHERE (table_schema, table_name, table_type) = ($1, $2, 'BASE TABLE'));
$$ language sql STRICT;

CREATE OR REPLACE FUNCTION __table_is_empty(TEXT) RETURNS bool as $$
SELECT not exists(SELECT 1 FROM $1 );
$$ language sql STRICT;

-- Start migration here

SELECT __execute($$
DROP TABLE oldtable1;
$$)
WHERE __table_exists('public', 'oldtable1')
AND __table_is_empty('oldtable1');

-- drop auxilary functions here

最后我得到了:

ERROR:  syntax error at or near "$1"
LINE 11: SELECT not exists(SELECT 1 FROM $1 );

还有其他办法吗?

最佳答案

如果您想在 Postgres 函数中将表名作为参数传递,则必须使用 EXECUTE
示例:

CREATE OR REPLACE FUNCTION __table_is_empty(param character varying) 
RETURNS bool
AS $$
DECLARE
v int;
BEGIN
EXECUTE 'select 1 WHERE EXISTS( SELECT 1 FROM ' || quote_ident(param) || ' ) '
INTO v;
IF v THEN return false; ELSE return true; END IF;
END;
$$ LANGUAGE plpgsql;
/

演示:http://sqlfiddle.com/#!12/09cb0/1

关于sql - 检查表在运行时是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26943904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com