在 to_regclass() 函数中使用动态创建的名称
Use dynamically created name in to_regclass() function
我已经动态创建了 table 名称,我需要检查这个 table 是否存在,为此我这样做:
....
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;
同样的错误,我哪里错了?如何正确执行此操作?
\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)
你必须使用转换为 cstring
另一种方式
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
我已经动态创建了 table 名称,我需要检查这个 table 是否存在,为此我这样做:
....
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;
同样的错误,我哪里错了?如何正确执行此操作?
\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)
你必须使用转换为 cstring
另一种方式
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