表:
Id Name Age Country
1 AAAA 12 AU
2 BBBB 13 CC
如何将结果作为KEYVALUE PAIR的TAB获取列名和相应的值?例如,对于id 1,结果应该类似于
[
{Name:AAAA},
{Age: 12},
{Country: AU}
]
答案 0 :(得分:2)
您可以使用UNPVIVOT
和LISTAGG
。
SELECT ID,
'['||
LISTAGG ('{' || col || ':' || VALUE || '}', ',')
WITHIN GROUP (ORDER BY ROWNUM)
|| ']' key_value_pair
FROM (SELECT id,Name, TO_CHAR (age) age, Country FROM yourtable)
UNPIVOT (VALUE FOR col IN (Name, Age, Country))
GROUP BY id;
<强>输出强>
| ID | KEY_VALUE_PAIR |
|----|-------------------------------------|
| 1 | [{NAME:AAAA},{AGE:12},{COUNTRY:AU}] |
| 2 | [{NAME:BBBB},{AGE:13},{COUNTRY:CC}] |
你说你有TYPE KEYVALUEPAIR<VARCHAR,VARCHAR>
。你可能想要使用这样的东西吗?
DECLARE
TYPE KEYVALUEPAIR
IS
RECORD
(
KEY_ VARCHAR2(12),
VALUE_ VARCHAR2(12) );
TYPE RECTYPE IS VARRAY(10) OF KEYVALUEPAIR;
RECID1 RECTYPE;
BEGIN
SELECT col,
VALUE BULK COLLECT
INTO RECID1
FROM
(SELECT id, Name, TO_CHAR (age) age, Country FROM yourtable WHERE ID = 1
) UNPIVOT (VALUE FOR col IN (Name, Age, Country)) ;
END;
/
答案 1 :(得分:0)
我不确定您的主要请求是使用VARARY集合还是以您提到的格式获取数据。
如果您需要使用VARRAY集合,请举例如下:
declare
type t_1 is varray(10) of test_1%ROWTYPE;
v_1 t_1:=t_1();
j number;
begin
v_1.extend(2);
j := 1;
for i in (select * from test_1)
loop
v_1(j).id := i.id;
v_1(j).name := i.name;
v_1(j).age := i.age;
v_1(j).country := i.country;
j := j + 1;
end loop;
for j in v_1.first .. v_1.last
loop
dbms_output.put_line ('v_1(' || j || ').id = ' || v_1(j).id);
dbms_output.put_line ('v_1(' || j || ').name = ' || v_1(j).name);
dbms_output.put_line ('v_1(' || j || ').age = ' || v_1(j).age);
dbms_output.put_line ('v_1(' || j || ').country = ' || v_1(j).country);
dbms_output.put_line ('---------------------------------');
end loop;
end;