Oracle 中的动态列名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11312499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic column name in Oracle
提问by Maki
I'm trying to dynamically set a column header.
我正在尝试动态设置列标题。
Here the example:
这里的例子:
SELECT Name, COUNT(cars) AS (('cars_from_year_') || year)
FROM peaple
WHERE car = 'GM'
AND Date BETWEEN (year || '0401') AND (year || '0430');
The year
should be for ex. 2012 and change (i.e. this being dynamic) for every year (2013,2014,...).
本year
应该是前。2012 年和每年(2013、2014 年,...)的变化(即这是动态的)。
I know the call select to_char(sysdate,'YYYY') from dual
but not how to implement it the select statement above?
我知道调用select to_char(sysdate,'YYYY') from dual
但不知道如何实现上面的 select 语句?
回答by Vincent Malgrat
Column names must be known at compile time. You obviously want to use dynamic column names so you will need to postpone the compilation until the actual execution. There are several ways to do this: DBMS_SQL
, EXECUTE IMMEDIATE
and REF CURSOR
for example.
在编译时必须知道列名。您显然想使用动态列名,因此您需要将编译推迟到实际执行。有几种方法可以做到这一点:DBMS_SQL
,EXECUTE IMMEDIATE
和REF CURSOR
例如。
Here's an example with REF CURSOR
and SQL*Plus
:
这是一个带有REF CURSOR
and的例子SQL*Plus
:
SQL> var x refcursor
SQL> DECLARE
2 l_year NUMBER := 2012;
3 BEGIN
4 OPEN :x
5 FOR 'SELECT ''This is the year ''||:year AS "Year ' || l_year || '"
6 FROM DUAL'
7 USING l_year;
8 END;
9 /
PL/SQL procedure successfully completed.
SQL> print x
Year 2012
--------------------------
This is the year 2012
回答by hkutluay
回答by glh
Try the pivot comands now available in 11g otherwise pl/sql is your only option as per Vincent Malgrat.
尝试现在在 11g 中可用的枢轴命令,否则按照 Vincent Malgrat 的说法,pl/sql 是您唯一的选择。
Nice question!
好问题!