我认为以下存储过程可以满足您的需要:
create or replace procedure expandcolumn
(
colname in varchar2
) as
v_max integer;
v_col_index integer := 0;
v_sql_ddl varchar2(2000) := 'alter table demo add (';
v_sql_update varchar2(2000) := 'update demo set ';
v_sep varchar2(3) := ', ';
begin
-- Retrieve the maximum value of the column so we know how many columns to add
execute immediate 'select max(' || colname || ') from demo' into v_max;
-- Starting from zero, prepare the DDL and UPDATE statements for each new column
for v_col_index in 0..v_max loop
if v_col_index = v_max then
v_sep := null; -- We don't need a comma separator after the last column
end if;
v_sql_ddl := v_sql_ddl || colname || '_' || v_col_index || ' number(1)' || v_sep;
v_sql_update := v_sql_update || colname || '_' || v_col_index ||
'=decode(' || colname || ',' || v_col_index || ', 1, 0)' || v_sep;
end loop;
v_sql_ddl := v_sql_ddl || ')';
execute immediate v_sql_ddl; -- Add the new columns to the demo table
execute immediate v_sql_update; -- Set the new column values (implicit commit)
end expandcolumn;
使用您希望扩展为多列的原始列名调用它,例如
create table demo (u number(1));
insert into demo values (0);
insert into demo values (2);
insert into demo values (1);
commit;
exec expandcolumn('U');
select * from demo;
U U_0 U_1 U_2
---------- ---------- ---------- ----------
0 1 0 0
2 0 0 1
1 0 1 0
当然,您可能需要参数化更多的东西(例如表名和列宽),但为了简单起见,我将它们省略了。