【发布时间】:2014-03-29 17:00:11
【问题描述】:
首先,我对 Oracle PLSQL 真的很生疏,我看到有几个人说这不能做到,而其他人说可以,但我就是无法做到。任何帮助将不胜感激。
我正在尝试动态读取记录类型中列的值。
我有一条带有标记的消息,我需要用记录集中的值替换标记。
所以消息看起来像:[status] by [agent_name]
我在另一个地方解析令牌。
在 java 脚本中,我知道这可以通过以下方式完成:(将在控制台中运行)
var record = {
status : "Open",
agent_name : "John"
};
var record2 = {
status : "Close",
agent_name : "Joe"
};
var records = [record, record2];
var token1 = "status";
var token2 = "agent_name";
for( var i=0; i<records.length; i++){
console.log(records[i][token1] + " by " + records[i][token2]);
}
Results : Open by John
Close by Joe
我想在 PLSQL 中做同样的事情
这是我的测试 PLSQL:
SET SERVEROUTPUT ON;
declare
TYPE my_record is RECORD
(
status VARCHAR2(30),
agent_name varchar2(30)
);
TYPE my_record_array IS VARRAY(6) OF my_record;
v_records my_record_array := my_record_array();
v_current_rec my_record;
v_current_rec2 my_record;
v_token varchar2(50):= 'agent_name';
v_token2 varchar2(50):= 'status';
begin
v_current_rec.status := 'Open';
v_current_rec.agent_name := 'John';
v_records.extend;
v_records(1) := v_current_rec;
v_current_rec2.status := 'Close';
v_current_rec2.agent_name := 'Ron';
v_records.extend;
v_records(2) := v_current_rec2;
FOR i IN 1..v_records.COUNT LOOP
--Hard coded
DBMS_OUTPUT.PUT_LINE(v_records(i).status || ' by ' || v_records(i).agent_name);
--Substitution vars entering v_records(i).status and v_records(i).agent_name for the prompts.
--How to do this without user interaction.
DBMS_OUTPUT.PUT_LINE(&status || ' by ' || &agent_name);
--Dynamically that doesn't work. How would this be accomplished
DBMS_OUTPUT.PUT_LINE(v_records(i).v_token || ' by ' || v_records(i).v_token2);
END LOOP;
END;
我尝试使用替换变量,如果我使用它会起作用:
DBMS_OUTPUT.PUT_LINE(&agent_name) 并在出现提示时输入 v_records(i).agent_name。我如何即时完成这项工作?
回答:
set serveroutput on;
DECLARE
type sr_record_map
IS
TABLE OF VARCHAR2(30) INDEX BY VARCHAR2(30);
type record_set
is
TABLE of sr_record_map index by BINARY_INTEGER;
v_current_rec sr_record_map;
v_record_set record_set;
v_token varchar2(30) := 'status';
v_token2 varchar2(30) := 'agent_name';
v_index number :=1;
begin
v_current_rec('status') := 'Open';
v_current_rec('agent_name') := 'John';
v_record_set(1) := v_current_rec;
v_current_rec('status') := 'Close';
v_current_rec('agent_name') := 'Joe';
v_record_set(2) := v_current_rec;
FOR i in 1..v_record_set.COUNT LOOP
v_current_rec := v_record_set(i);
DBMS_OUTPUT.PUT_LINE(v_current_rec(v_token) || ' by ' || v_current_rec(v_token2));
END LOOP;
end;
【问题讨论】:
-
您说,您的记录可能有任何成员(列),您想通过选择一个来打印它们?
-
我有多条消息,可能有任意数量的令牌。我知道这些字段存在于记录中。因此,如果我有一个令牌 agent_name,我想评估字符串 v_records(i).agent_name 并从记录中获取值。所以我可以用值替换消息中的令牌。
标签: sql oracle dynamic plsql plsqldeveloper