1

我已经动态创建了表名,我需要检查这个表是否存在,为此我这样做:

....
SELECT to_regclass('public.tableprefix_'||variable_name) INTO table_exists;
IF table_exists IS NULL THEN 
    RETURN 'NOT EXISTS';
ELSE
    RETURN 'EXISTS';
END IF;
....

这给出了错误function to_regclass(text) does not exist

然后我尝试显式类型转换:

SELECT to_regclass('public.tableprefix_'||variable_name::regclass) INTO table_exists;

但同样的错误,我错在哪里?如何正确执行此操作?

4

2 回答 2

2

\df to_regclass

postgres=# \df to_regclass 
                              List of functions
┌────────────┬─────────────┬──────────────────┬─────────────────────┬────────┐
│   Schema   │    Name     │ Result data type │ Argument data types │  Type  │
├────────────┼─────────────┼──────────────────┼─────────────────────┼────────┤
│ pg_catalog │ to_regclass │ regclass         │ cstring             │ normal │
└────────────┴─────────────┴──────────────────┴─────────────────────┴────────┘
(1 row)

你必须使用 cast 来cstring

于 2015-11-27T08:29:58.373 回答
1

另一种方式

 declare 
table_exists boolean;

begin

select EXISTS (
    SELECT 1
    FROM information_schema.tables
    WHERE table_schema = 'public'
        AND table_name = 'tableprefix_' || variable_name || ''
    ) into table_exists;

If  table_exists =true then
RETURN ' EXISTS';
else
RETURN 'NOT EXISTS';
end IF;

end 
于 2015-11-27T08:35:12.467 回答