試試這個:
create table schema1.tableA
(field_1 char(1),
field_2 varchar(10));
insert into schema1.tableA
values ('A','table_10'),
('B','table_20'),
('C','table_30');
create table schema2.table_10
(field_1 dec(5,0));
insert into schema2.table_10
values (20), (30), (40);
create table schema2.table_20
(field_1 dec(5,0));
insert into schema2.table_20
values (6), (9), (12);
create table schema2.table_30
(field_1 dec(5,0));
insert into schema2.table_30
values (10), (15), (20);
with tmp (table_name, field_1) as (
select 'table_10', max(field_1) from schema2.table_10
union all
select 'table_20', max(field_1) from schema2.table_20
union all
select 'table_30', max(field_1) from schema2.table_30)
select a.field_1, b.field_1
from schema1.tableA a
join tmp b on b.table_name = a.field_2;
如果你有太多的表,以使上述工作,你可以使用一個用戶定義的函數是這樣的:
create or replace function MaxNbr
(p_TableName varchar(128),
p_TableSchema varchar(128))
Returns dec(5,0)
language sql
not deterministic
no external action
reads sql data
returns null on null input
not fenced
begin
declare l_stmt varchar(1024);
declare l_table varchar(128);
declare l_schema varchar(128);
declare l_result dec(5,0);
set l_table = replace(upper(p_TableName),'"','');
set l_schema = replace(upper(p_TableSchema),'"','');
set l_stmt = 'values (select max(field_1) from "' || l_schema || '"."' ||
trim(l_table) || '") into ?';
prepare S1 from l_stmt;
allocate sql descriptor 'D1';
describe S1 using sql descriptor 'D1';
execute S1 into sql descriptor 'D1';
get sql descriptor 'D1' value 1 l_result = data;
deallocate sql descriptor 'D1';
return l_result;
end;
這是必要的,因爲您不能將變量用於標識符,如表名稱或模式名稱。
要使用用戶定義的函數,你可以這樣做:
set schema schema1;
set path = udf_schema;
select field_1, MaxNbr(field_2, 'schema2') as field_2
from tableA;
感謝。但是如果SCHEMA_2包含3個以上的表格,我能做些什麼?例如50個具有相同字段的表。 – Asset
你將不得不編寫一個UDF來從表中獲取數量。不幸的是,沒有辦法將表名稱編碼爲變量。 – jmarkmurphy
確保您抵禦注射。 – jmarkmurphy