通过列名动态访问游标
我可以动态访问游标的列吗?我的意思是名字?像这样的东西:
declare
v_cursor := select * from emp;
begin
FOR reg IN v_cursor LOOP
dbms_output.put_line(**reg['column_name_as_string']**);
end loop;
end;
我知道粗体部分不是 PL/SQL,但我正在寻找类似的东西,但在任何地方都找不到它。
Can I access a cursor's column dynamically? I mean by name? something like this:
declare
v_cursor := select * from emp;
begin
FOR reg IN v_cursor LOOP
dbms_output.put_line(**reg['column_name_as_string']**);
end loop;
end;
I know the bold part is not PL/SQL, but I'm looking for something like that and can't find it anywhere.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用包
DBMS_SQL
使用动态查询创建和访问游标。然而,通过名称访问列并不是很简单,因为 DBMS_SQL 包使用定位,并且在动态查询中,我们在执行之前可能不知道列的顺序。
此外,在这个问题的上下文中,我们似乎可能不知道在编译时要显示哪一列,我们将假设我们要显示的列作为参数给出。
我们可以使用
DBMS_SQL.describe_columns
在解析SELECT
查询的列以构建列的动态映射后对其进行分析。我们假设所有列都可以转换为VARCHAR2
,因为我们希望使用DBMS_OUTPUT
显示它们。下面是一个示例:
我们可以使用仅在运行时已知的查询来调用此过程:
使用动态 SQL 时要小心:它具有与用户相同的权限,因此可以执行允许的任何 DML 和 DDL 语句对于这个模式。
例如,上述过程可用于创建或删除表:
You can use the package
DBMS_SQL
to create and access cursors with dynamic queries.However it's not really straightforward to access a column by name because the
DBMS_SQL
package uses positioning and in a dynamic query we may not know the order of the columns before the execution.Furthermore, in the context of this question, it appears that we may not know which column we want to display at compile time, we will assume that the column we want to display is given as a parameter.
We can use
DBMS_SQL.describe_columns
to analyze the columns of aSELECT
query after it has been parsed to build a dynamic mapping of the columns. We will assume that all columns can be cast intoVARCHAR2
since we want to display them withDBMS_OUTPUT
.Here's an example:
We can call this procedure with a query known only at run-time:
Use caution with dynamic SQL: it has the same privileges as the user and can therefore execute any DML and DDL statement allowed for this schema.
For instance, the above procedure could be used to create or drop a table:
如果可以的话,使查询动态化可能是最简单的。
如果您确实想要一个硬编码的 SELECT * 并按名称动态选择列,我认为您可以按照 Vincent 的建议使用 DBMS_SQL 来实现,但它会更复杂一些。
It's probably easiest to make the query dynamic if you can.
If you really want to have a hardcoded
SELECT *
and dynamically select a column from that by name, I think you could do that using DBMS_SQL as Vincent suggests, but it will be somewhat more complex.你的意思是这样的:
You mean something like: