相关疑难解决方法(0)

如何检查给定模式中是否存在表

Postgres 8.4及更高版本的数据库包含public模式中的模式和公司特定表中的公用表company.
company模式名称始终'company'以公司编号开头并以公司编号结束.
所以可能有以下模式:

public
company1
company2
company3
...
companynn
Run Code Online (Sandbox Code Playgroud)

应用程序始终适用于单个公司.
search_path相应指定在ODBC或连接Npgsql的字符串,如:

search_path='company3,public'
Run Code Online (Sandbox Code Playgroud)

如何检查给定表是否存在于指定的companyn模式中?

例如:

select isSpecific('company3','tablenotincompany3schema')
Run Code Online (Sandbox Code Playgroud)

应该返回false,并

select isSpecific('company3','tableincompany3schema')
Run Code Online (Sandbox Code Playgroud)

应该回来true.

在任何情况下,该函数应仅检查companyn传递的模式,而不检查其他模式.

如果两者public和传递的模式中都存在给定的表,则该函数应该返回true.
它适用于Postgres 8.4或更高版本.

sql database postgresql information-schema search-path

133
推荐指数
2
解决办法
14万
查看次数

表名作为PostgreSQL函数参数

我想在Postgres函数中传递一个表名作为参数.我试过这段代码:

CREATE OR REPLACE FUNCTION some_f(param character varying) RETURNS integer 
AS $$
    BEGIN
    IF EXISTS (select * from quote_ident($1) where quote_ident($1).id=1) THEN
     return 1;
    END IF;
    return 0;
    END;
$$ LANGUAGE plpgsql;

select some_f('table_name');
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

ERROR:  syntax error at or near "."
LINE 4: ...elect * from quote_ident($1) where quote_ident($1).id=1)...
                                                             ^

********** Error **********

ERROR: syntax error at or near "."
Run Code Online (Sandbox Code Playgroud)

以下是更改为此时出现的错误select * from quote_ident($1) tab where tab.id=1:

ERROR:  column tab.id does not exist
LINE 1: ...T EXISTS …
Run Code Online (Sandbox Code Playgroud)

postgresql function dynamic-sql plpgsql identifier

69
推荐指数
4
解决办法
7万
查看次数

循环并从多个表中选择数据的函数

我是Postgres的新手,拥有一个具有相同结构的多个表的数据库.我需要从每个表中选择符合特定条件的数据.

我可以通过一堆UNION查询来做到这一点,但是我需要搜索的表的数量会随着时间的推移而改变,所以我不想像那样硬编码.我一直在尝试开发一个循环遍历特定表的函数(它们有一个共同的命名约定)并返回一个记录表,但是当我查询函数时,我没有得到任何结果.功能代码如下:

CREATE OR REPLACE FUNCTION public.internalid_formaltable_name_lookup()
  RETURNS TABLE(natural_id text, name text, natural_id_numeric text) AS
$BODY$
DECLARE
    formal_table text;
begin
  FOR formal_table IN
    select table_name from information_schema.tables
    where table_schema = 'public' and table_name like 'formaltable%'
  LOOP
    EXECUTE 'SELECT natural_id, name, natural_id_numeric
             FROM ' || formal_table || 
           ' WHERE natural_id_numeric IN (
                select natural_id_numeric from internal_idlookup
                where internal_id = ''7166571'')';
    RETURN NEXT;
 END LOOP;
 Return;
END;
$BODY$
  LANGUAGE plpgsql;
Run Code Online (Sandbox Code Playgroud)

我尝试使用该函数时没有收到任何错误,但它没有返回任何行:

SELECT * From internalid_formaltable_name_lookup();
Run Code Online (Sandbox Code Playgroud)

知道我哪里错了吗?

postgresql for-loop dynamic-sql plpgsql set-returning-functions

10
推荐指数
1
解决办法
4万
查看次数