gpt4 book ai didi

Oracle - 从引用游标中选择特定列

转载 作者:行者123 更新时间:2023-12-04 03:33:31 24 4
gpt4 key购买 nike

我有一个名为 Table1 的表。它有很多列,其中之一是 Column1。我不知道其他列,它们有时甚至可能会发生变化。有一个强类型引用游标类型,它返回 Table1%rowtype,名为 cur_Table1。我有一个名为 SP1 的存储过程,它有一个类型为 cur_Table1 的输出参数。我正在从另一个数据库调用这个 SP1 存储过程,该数据库只看到这个存储过程,而不是表或类型本身。如何从返回的游标中仅选择 Column1?我知道我可以获取一条记录或与游标具有的列一样多的变量,但我只知道一列的存在,因此我无法声明完整的记录或正确数量的变量。

最佳答案

你可以用 DBMS_SQL 来做到这一点,但它不漂亮。

表和示例数据(COLUMN1 的编号为 1 - 10):

create table table1(column1 number, column2 date, column3 varchar2(1000), column4 clob);

insert into table1
select level, sysdate, level, level from dual connect by level <= 10;
commit;

带有打开引用光标并选择所有内容的过程的包:
create or replace package test_pkg is
type cur_Table1 is ref cursor return table1%rowtype;
procedure sp1(p_cursor in out cur_table1);
end;
/

create or replace package body test_pkg is
procedure sp1(p_cursor in out cur_table1) is
begin
open p_cursor for select column1, column2, column3, column4 from table1;
end;
end;
/

从引用游标读取 COLUMN1 数据的 PL/SQL 块:
--Basic steps are: call procedure, convert cursor, describe and find columns,
--then fetch rows and retrieve column values.
--
--Each possible data type for COLUMN1 needs to be added here.
--Currently only NUMBER is supported.
declare
v_cursor sys_refcursor;
v_cursor_number number;

v_columns number;
v_desc_tab dbms_sql.desc_tab;
v_position number;
v_typecode number;
v_number_value number;
begin
--Call procedure to open cursor
test_pkg.sp1(v_cursor);
--Convert cursor to DBMS_SQL cursor
v_cursor_number := dbms_sql.to_cursor_number(rc => v_cursor);
--Get information on the columns
dbms_sql.describe_columns(v_cursor_number, v_columns, v_desc_tab);

--Loop through all the columns, find COLUMN1 position and type
for i in 1 .. v_desc_tab.count loop
if v_desc_tab(i).col_name = 'COLUMN1' then
v_position := i;
v_typecode := v_desc_tab(i).col_type;

--Pick COLUMN1 to be selected.
if v_typecode = dbms_types.typecode_number then
dbms_sql.define_column(v_cursor_number, i, v_number_value);
--...repeat for every possible type.
end if;
end if;
end loop;

--Fetch all the rows, then get the relevant column value and print it
while dbms_sql.fetch_rows(v_cursor_number) > 0 loop
if v_typecode = dbms_types.typecode_number then
dbms_sql.column_value(v_cursor_number, v_position, v_number_value);
dbms_output.put_line('Value: '||v_number_value);
--...repeat for every possible type
end if;
end loop;
end;
/

关于Oracle - 从引用游标中选择特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10321571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com