Oracle:使列名动态化

时间:2013-01-28 18:38:20

标签: oracle

我有一张桌子,其中的月份如下:

product rev_jan unit_jan prod_jan rev_feb  rev_march u...

我需要获取当月的数据。

目前我正在使用绑定变量。

select 
rev_&1,
prod_&1,
unit_&1
from 
table_name

是否有更好的方法解决方案,因为在这种方法中我必须提示3个月。

1 个答案:

答案 0 :(得分:2)

OP描述的是在sqlplus“命令行”上为sqlplus脚本提供参数。如果文件包含以下内容:

select 
rev_&1,
prod_&1,
unit_&1
from 
table_name;

然后sqlplus将从提示符中获取第一个“命令行参数”,例如

SQL> @script.sql arg1

并使用文字值arg1替换'& 1'而不提示三次(或者在脚本中出现子字符串'& 1'的次数)。

如果你没有在“命令行”中提供参数,那么sqlplus每次出现在脚本中时都会提示“& 1”的值(这里是3次)。

避免使用'&'由sqlplus解释的字符,你可以使用sqlplus的“set define off”或连接单个'&'字符串中的字符文字:'AT' || '&' || 'T'

或者,您可以在脚本中设置提示以提高可读性:

accept a_month prompt 'Please enter the desired month: '
select 
    rev_&a_month,
    prod_&a_month,
    unit_&a_month
    from 
    table_name;

然后,从sqlplus提示符调用脚本,如下所示:

SQL> @script.sql
Please enter the desired month: jan

(脚本在这里执行。)

有关sqlplus参考,请参阅Oracle manual