我们可以在 Select 查询中使用什么来代替游标

What can we use in Select Query instead of cursor

我不想在我的 select 查询中直接使用游标,但我找不到任何其他使用方法。

我的第一个查询是

 select 'Joe' as Name,'Last' as LastName, cursor(select * from temp) as Details from dual;

Table 温度:

A B C
1 2 3
2 3 4

输出:

Name LastName Details
Joe Last {<A=1,B=2,C=3>,<A=2,B=3,C=4>,}

我不想在 select 查询中直接使用游标。 "cursor(select * from temp) as details"?

有任何不同的用法吗

如果可以在Declare begin end 语句中,也可以。当我尝试以下方式时出现错误。

DECLARE
cursor cur is (select * from temp);
x cur%rowtype
BEGIN

open cur;
loop
fetch cur into x;
end loop;
close cur;

SELECT NAME,LASTNAME,CUR FROM DUAL;

END;

错误: 表达式类型错误

那么,你想得到什么结果?

这是你现在拥有的:

SQL> select 'Joe','Last', cursor(select * from dept) as details from dual;

'JO 'LAS DETAILS
--- ---- --------------------
Joe Last CURSOR STATEMENT : 3

CURSOR STATEMENT : 3

    DEPTNO DNAME          LOC
---------- -------------- -------------
        10 ACCOUNTING     NEW YORK
        20 RESEARCH       DALLAS
        30 SALES          CHICAGO
        40 OPERATIONS     BOSTON


SQL>

你可以吗?

SQL> select 'Joe', 'Last', d.deptno, d.dname, d.loc from dept d;

'JO 'LAS     DEPTNO DNAME          LOC
--- ---- ---------- -------------- -------------
Joe Last         10 ACCOUNTING     NEW YORK
Joe Last         20 RESEARCH       DALLAS
Joe Last         30 SALES          CHICAGO
Joe Last         40 OPERATIONS     BOSTON

SQL>

[编辑]:returns refcursor

的函数
SQL> create or replace function f_temp return sys_refcursor is
  2    l_rc sys_refcursor;
  3  begin
  4    open l_rc for select * from temp;
  5    return l_rc;
  6  end;
  7  /

Function created.

SQL> select 'Joe','Last', f_temp
  2  from dual;

'JO 'LAS F_TEMP
--- ---- --------------------
Joe Last CURSOR STATEMENT : 3

CURSOR STATEMENT : 3

         A          B          C
---------- ---------- ----------
         1          2          3
         2          3          4


SQL>

您可以将光标换行到xmltype() ,例如:

select
 'Joe'
,'Last'
,xmltype (cursor(select * from temp)) as details 
from dual

您可以创建一个 returns 所需字符串的函数,然后在 SELECT

中调用该函数
select 'Joe' as Name,'Last' as LastName, funcDesiredString() as Details from dual;

函数的逻辑是这样的-

desiredDetails := '{';
for rec in (Select A, B, C from Temp)
Loop
 desiredDetails := desiredDetails || '<A=' || rec.A || ',B=' || rec.B || ',C=' || rec.C || '>,'; 
End Loop;
desiredDetails := TRIM(','  FROM  desiredDetails);
desiredDetails := desiredDetails || '}';