gpt4 book ai didi

sql - oracle 10g从单个select语句中获取所有选定的列和数据类型

转载 作者:行者123 更新时间:2023-12-02 05:09:10 26 4
gpt4 key购买 nike

我想从单个 select 语句中获取所有选定的列,而不执行执行。查询可能使用join或union,那么查询可能不止一张表,所以我不能简单地使用语句

select column_name, data_type
from user_tab_cols
where table_name = 'my_table_name'

得到结果。

例如

输入:

select db1.*
from (select dept_code,
vital_signs,
units,
log_time
from table1
where dept_code = '111'
union
select 'hl06' as dept_code,
vital_signs,
units,
log_time
from table2
where isdefault = 1
and vital_signs not in
(select vital_signs
from Ward_Vs_Vital_Signs
where dept_code = '111')) db1,
table3 db2
where db1.vital_signs = db2.vital_signs(+)
order by db2.serial_no

输出:

column_name  | data_type
-------------------------
dept_code | VARCHAR
vital_signs | NUMBER
units | VARCHAR
log_time | DATE

我的问题是如何解析查询并要求数据库告诉我将返回的列和数据类型而不执行语句?谢谢!

PS:我使用的是 Oracle 10g。

最佳答案

使用单个 select 语句没有简单的方法来做到这一点,但是,您可以研究 dbms_sql 方法 ( DOC )。

    14:32:26 SYSTEM@dwal> ed
Wrote file S:\spool\dwal\BUFFER_SYSTEM_329.sql

1 DECLARE
2 c NUMBER;
3 d NUMBER;
4 col_cnt INTEGER;
5 rec_tab DBMS_SQL.DESC_TAB;
6 col_num NUMBER;
7 PROCEDURE print_rec(rec in DBMS_SQL.DESC_REC) IS
8 BEGIN
9 DBMS_OUTPUT.NEW_LINE;
10 DBMS_OUTPUT.PUT_LINE('col_name = ' || rec.col_name);
11 DBMS_OUTPUT.PUT_LINE('col_type = ' || rec.col_type);
12 END;
13 BEGIN
14 c := DBMS_SQL.OPEN_CURSOR;
15 DBMS_SQL.PARSE(c, 'SELECT dummy, 12345 num, sysdate dt FROM dual', DBMS_SQL.NATIVE);
16 d := DBMS_SQL.EXECUTE(c);
17 DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
18 col_num := rec_tab.first;
19 IF (col_num IS NOT NULL) THEN
20 for i in 1 .. col_cnt LOOP
21 print_rec(rec_tab(i));
22 END LOOP;
23 END IF;
24 DBMS_SQL.CLOSE_CURSOR(c);
25* END;
14:32:46 SYSTEM@dwal> /
col_name = DUMMY
col_type = 1
col_name = NUM
col_type = 2
col_name = DT
col_type = 12

PL/SQL procedure successfully completed.

注意上面的col_type数值 - 它是映射到实际数据类型的类型代码。映射记录如下:http://docs.oracle.com/cd/E11882_01/server.112/e17118/sql_elements001.htm#i54330

关于sql - oracle 10g从单个select语句中获取所有选定的列和数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18650835/

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