I have a name of table or view in PostgreSQL database and need to delete in in single pgSQL command. How can i afford it?
我在PostgreSQL数据库中有一个表或视图的名称,需要在单个pgSQL命令中删除。我怎么能买得起?
I was able to select form system table to find out if there any table with such a name but stuck with procedural part:
我能够选择表单系统表来查找是否有任何具有这样名称的表但是仍然存在程序部分:
SELECT count(*) FROM pg_tables where tablename='user_statistics';
2 个解决方案
#1
DROP TABLE user_statistics;
DROP VIEW user_statistics;
complete syntax:
And if you want a complete function, i tried something like this:
如果你想要一个完整的功能,我尝试过这样的事情:
CREATE OR REPLACE FUNCTION delete_table_or_view(objectName varchar) RETURNS integer AS $$
DECLARE
isTable integer;
isView integer;
BEGIN
SELECT INTO isTable count(*) FROM pg_tables where tablename=objectName;
SELECT INTO isView count(*) FROM pg_views where viewname=objectName;
IF isTable = 1 THEN
execute 'DROP TABLE ' || objectName;
RETURN 1;
END IF;
IF isView = 1 THEN
execute 'DROP VIEW ' || objectName;
RETURN 2;
END IF;
RETURN 0;
END;
$$ LANGUAGE plpgsql;
#2
Consider using DROP TABLE IF EXISTS and DROP VIEW IF EXISTS. That way you won't get an error message if it fails, just a notice.
考虑使用DROP TABLE IF EXISTS和DROP VIEW IF EXISTS。这样,如果失败,您将不会收到错误消息,只是一个通知。
#1
DROP TABLE user_statistics;
DROP VIEW user_statistics;
complete syntax:
And if you want a complete function, i tried something like this:
如果你想要一个完整的功能,我尝试过这样的事情:
CREATE OR REPLACE FUNCTION delete_table_or_view(objectName varchar) RETURNS integer AS $$
DECLARE
isTable integer;
isView integer;
BEGIN
SELECT INTO isTable count(*) FROM pg_tables where tablename=objectName;
SELECT INTO isView count(*) FROM pg_views where viewname=objectName;
IF isTable = 1 THEN
execute 'DROP TABLE ' || objectName;
RETURN 1;
END IF;
IF isView = 1 THEN
execute 'DROP VIEW ' || objectName;
RETURN 2;
END IF;
RETURN 0;
END;
$$ LANGUAGE plpgsql;
#2
Consider using DROP TABLE IF EXISTS and DROP VIEW IF EXISTS. That way you won't get an error message if it fails, just a notice.
考虑使用DROP TABLE IF EXISTS和DROP VIEW IF EXISTS。这样,如果失败,您将不会收到错误消息,只是一个通知。