亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在所有表中搜索特定值(PostgreSQL)?

如何在所有表中搜索特定值(PostgreSQL)?

www說 2019-09-20 17:06:56
是否可以在PostgreSQL中搜索每個表的每一列中的特定值?Oracle 提供了類似的問題。
查看完整描述

3 回答

?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

如果有人認為它可以幫助你。這是@DanielVérité的函數,另一個參數接受可以在搜索中使用的列的名稱。這樣可以減少處理時間。至少在我的測試中它減少了很多。


CREATE OR REPLACE FUNCTION search_columns(

    needle text,

    haystack_columns name[] default '{}',

    haystack_tables name[] default '{}',

    haystack_schema name[] default '{public}'

)

RETURNS table(schemaname text, tablename text, columnname text, rowctid text)

AS $$

begin

  FOR schemaname,tablename,columnname IN

      SELECT c.table_schema,c.table_name,c.column_name

      FROM information_schema.columns c

      JOIN information_schema.tables t ON

        (t.table_name=c.table_name AND t.table_schema=c.table_schema)

      WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')

        AND c.table_schema=ANY(haystack_schema)

        AND (c.column_name=ANY(haystack_columns) OR haystack_columns='{}')

        AND t.table_type='BASE TABLE'

  LOOP

    EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',

       schemaname,

       tablename,

       columnname,

       needle

    ) INTO rowctid;

    IF rowctid is not null THEN

      RETURN NEXT;

    END IF;

 END LOOP;

END;

$$ language plpgsql;

Bellow是上面創建的search_function的使用示例。


SELECT * FROM search_columns('86192700'

    , array(SELECT DISTINCT a.column_name::name FROM information_schema.columns AS a

            INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)

        WHERE 

            a.column_name iLIKE '%cep%' 

            AND b.table_type = 'BASE TABLE'

            AND b.table_schema = 'public'

    )


    , array(SELECT b.table_name::name FROM information_schema.columns AS a

            INNER JOIN information_schema.tables as b ON (b.table_catalog = a.table_catalog AND b.table_schema = a.table_schema AND b.table_name = a.table_name)

        WHERE 

            a.column_name iLIKE '%cep%' 

            AND b.table_type = 'BASE TABLE'

            AND b.table_schema = 'public')

);


查看完整回答
反對 回復 2019-09-20
  • 3 回答
  • 0 關注
  • 1390 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號