2016-10-13 3 views
1

something이라는 열이있는 테이블이 여러 개 있습니다.특정 열을 포함하는 모든 테이블에서 행 선택

이러한 열이있는 모든 테이블에서 열 something의 모든 행을 선택하려면 어떻게해야합니까?

하나의 쿼리로 수행 할 수 있습니까?

SELECT 'SELECT something FROM ' || table_name ||';' 
    FROM information_schema.columns 
    WHERE column_name = 'something' 

후 생성 된 스크립트의 출력을 실행 방법에

답변

3

동적 스크립트를 작성하는 것입니다. 스키마 이름, 열 유형, 공용체 등이 염려되는 경우 이에 따라 동적 SQL 생성을 수정하십시오.

0
begin; 
do $$ 
declare 
    stmt text; 
    tbls text[]; 
    col text := 'x'; 
begin 
    select 
    array_agg(format(
     'select ''%2$s.%3$s'' as tbl, %1$I::text from %2$I.%3$I', 
     col, table_schema, table_name)) 
    into tbls 
    from information_schema.columns 
    where column_name = col; 
    raise info '%', tbls; 
    stmt := array_to_string(tbls, ' union all '); 
    raise info '%', stmt; 
    execute 'declare foo cursor for ' || stmt; 
end $$; 
fetch all from foo; 
rollback; 

및 결과 (내 테스트 DB에 대한)입니다 :

INFO: {"select 'public.dummy' as tbl, x::text from public.dummy","select 'nd.t' as tbl, x::text from nd.t"} 
INFO: select 'public.dummy' as tbl, x::text from public.dummy union all select 'nd.t' as tbl, x::text from nd.t 
╔══════════════╤═══╗ 
║  tbl  │ x ║ 
╠══════════════╪═══╣ 
║ public.dummy │ X ║ 
║ nd.t   │ 3 ║ 
╚══════════════╧═══╝ 
(2 rows) 

declare ... 문에 의해 생성 된 커서는 트랜잭션에 존재하기 때문에이 단일 트랜잭션 (begin; ... rollback;)에서 실행해야합니다.

관련 문제