Rewrite the static query in dynamic SQL
Can someone please help me write a dynamic query in pl/sql to SQL next?It's the game ('25', ' 04 "). the number of list might be n.
The column_type varies from(1..6) and
the from(1..6) of column_amt1 lines
SELECT t.claim_no, t.cert_no, t.rec_code,
(NVL(decode(t.column_type1,'25',NVL (t.column_amt1, 0)),0)+
NVL(decode(t.column_type1,'04',NVL(t.column_amt1, 0)),0 )
)
+
(NVL(decode(t.column_type2,'25',NVL (t.column_amt2, 0)),0)+
NVL(decode(t.column_type2,'04',NVL(t.column_amt2, 0)),0 )
)
+
(NVL(decode(t.column_type3,'25',NVL (t.column_amt3, 0)),0)+
NVL(decode(t.column_type3,'04',NVL(t.column_amt3, 0)),0 )
)
+
(NVL(decode(t.column_type4,'25',NVL (t.column_amt4, 0)),0)+
NVL(decode(t.column_type4,'04',NVL(t.column_amt4, 0)),0 )
)
+
(NVL(decode(t.column_type5,'25',NVL (t.column_amt5, 0)),0)+
NVL(decode(t.column_type5,'04',NVL(t.column_amt5, 0)),0 )
)
+
(NVL(decode(t.column_type6,'25',NVL (t.column_amt6, 0)),0)+
NVL(decode(t.column_type6,'04',NVL(t.column_amt6, 0)),0 )) amt from test_detail t;
Thanks in advanceHena
But in fact, you should not dynamic SQL at all. What you could do is create a SQL type and use MEMBER OF:
SQL> CREATE OR REPLACE
2 TYPE test_detail_type_tbl
3 AS
4 TABLE OF varchar2(2)
5 /
Type created.
SQL> select case_id,
2 item,
3 code,
4 case
5 when type1 member of test_detail_type_tbl('25','04') then nvl(amt1,0)
6 else 0
7 end +
8 case
9 when type2 member of test_detail_type_tbl('25','04') then nvl(amt2,0)
10 else 0
11 end +
12 case
13 when type3 member of test_detail_type_tbl('25','04') then nvl(amt3,0)
14 else 0
15 end +
16 case
17 when type4 member of test_detail_type_tbl('25','04') then nvl(amt4,0)
18 else 0
19 end +
20 case
21 when type5 member of test_detail_type_tbl('25','04') then nvl(amt5,0)
22 else 0
23 end +
24 case
25 when type6 member of test_detail_type_tbl('25','04') then nvl(amt6,0)
26 else 0
27 end copay
28 from test_detail
29 /
CASE_ID ITEM CO COPAY
---------- --------- -- ----------
EML3371015 133761570 10 355
EML3371015 133761570 10 20
EML3371015 133761570 10 5
EMC6369600 140328551 10 54
EMH6353995 140328551 11 26.04
SQL> select case_id,
2 item,
3 code,
4 case
5 when type1 member of test_detail_type_tbl('25') then nvl(amt1,0)
6 else 0
7 end +
8 case
9 when type2 member of test_detail_type_tbl('25') then nvl(amt2,0)
10 else 0
11 end +
12 case
13 when type3 member of test_detail_type_tbl('25') then nvl(amt3,0)
14 else 0
15 end +
16 case
17 when type4 member of test_detail_type_tbl('25') then nvl(amt4,0)
18 else 0
19 end +
20 case
21 when type5 member of test_detail_type_tbl('25') then nvl(amt5,0)
22 else 0
23 end +
24 case
25 when type6 member of test_detail_type_tbl('25') then nvl(amt6,0)
26 else 0
27 end copay
28 from test_detail
29 /
CASE_ID ITEM CO COPAY
---------- --------- -- ----------
EML3371015 133761570 10 300
EML3371015 133761570 10 20
EML3371015 133761570 10 5
EMC6369600 140328551 10 0
EMH6353995 140328551 11 5.52
SQL>
SY.
Tags: Database
Similar Questions
-
Difference between the static SQL query and dynamic SQL query.
Hello
Please explain the fundamental difference between static and dynamic sql queries. Please explain for example.Static: http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/static.htm
Dynamics: http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10472/dynamic.htm -
Is it possible to keep all static? (vs dynamic SQL)?
Hi all
I have existing MS who after db Exchange should work with newly partitioned table partition name = date of entry both inside AND date_param, something like:
sql_string: =' select * tt partition (P_'| date_param |') the problem of configuration required, I can't use any dynamic SQL and it really put me in the corner, do you think it is at all possible? I was thinking about a lot of things that may work, but date_param is just date < 12 - 7.-10. > and partition is preceded with PRT_?
I can to with str_part: = ('(P_'|| date_param ||'') ') "), but it is already dynamic...
Even after I create the temporary table and for sure, I know that the DDL inside the procedure should be ONLY dynamic?
What is the dead end? There is a way to CREATE static? or simply to use kind of temp table created outside MS and clean it before use? or...
I actually try to see why customer site cannot manage NDS or they just don't want it, but can't argue with that for now.
I've got enough new to Oracle and couldn't do bad things on the SQL dynamic (NDS)?
Thank you all
TRTrento wrote:
Hi allI have existing MS who after db Exchange should work with newly partitioned table partition name = date of entry both inside AND date_param, something like:
sql_string: =' select * tt partition (P_'| date_param |') the problem of configuration required, I can't use any dynamic SQL and it really put me in the corner, do you think it is at all possible? I was thinking about a lot of things that may work, but date_param is just <12-Sep-10>and partition is preceded with PRT_?
I can to with tmp_part: = ('(PRT_'|| date_param ||'') ') "), but it is already dynamic...
Even after I create the temporary table and for sure, I know that the DDL inside the procedure should be ONLY dynamic?
What is the dead end? There is a way to CREATE static?I actually try to see why customer site cannot manage NDS or they do not want, cannot buy with that for now. I'm pretty new to Oracle and could not do bad things on dynamic SQL?
Thank you all
12-Sep-10>
TRWhy the hell wouldn't you just query the table and apply the predicate? Oracle would then partition elimination for you.
No need for anything either dynamics based on what you posted.
-
link: new values on after the trigger by using dynamic sql.
Hello all I have a problem I want to solve using dynamic sql on a trigger. The problem is that are around 5 qty fields who each have 18 separate fields. This is because of different sizes (S, M, L, XL, etc., up to 18). So I will try to use the: new values on a trigger to dynamically fill these information on a table, but immediate execution is run is returning the value like: new.open_sz (x) instead of the actual numeric value of the column. See code below. Is there a way to do this.
Thank you in advance.
CREATE OR REPLACE TRIGGER T_EXAMPLE
after update of
open_sz1, open_sz2, open_sz3, open_sz4, open_sz5, open_sz6,
open_sz7, open_sz8, open_sz9, open_sz10, open_sz11, open_sz12,
open_sz13, open_sz14, open_sz15, open_sz16, open_sz17, open_sz18
on order_li_m for each line
declare
Is of TYPE NumArray table indexes number directory;
NumArray v_orderqty;
-TYPE VarArray is the table of the varchar2 (200) index directory.
-v_orderqty K_A2KSTD. VarArray;
v_col varchar2 (30);
v_sql varchar2 (1000);
BEGIN
for a 1 in... 18 loop
v_col: = ': new.open_sz' | one;
v_sql: = ' SELECT: 1 double ';
run immediately v_sql in v_orderqty (a) using v_col;
dbms_output.put_line (v_orderqty (a));
end loop;
end T_EXAMPLE;
/Raffy Martin wrote:
Is there a way to do this.You may not use: news and: old identifiers in dynamic SQL, the way to do it is to specify the real column names.
-
ORA-00900 when you use the command COPY with dynamic SQL
Helllo,
I created the following procedure:
create or replace procedure copyTable (pSourceTableOwner IN varchar2
pSourceTableOwnerPasword IN varchar2
pTargetTableOwner IN varchar2
pTableName IN varchar2
pDatabaseLink IN varchar2)
as
vStatement varchar2 (250): = null;
Start
vStatement: = "copy of". pSourceTableOwner | '/' || pSourceTableOwnerPasword | '@' || pDatabaseLink |
"Insert" | pTargetTableOwner | '.' || pTableName | ' using select * from '. pTableName;
immediately run vStatement;
end;
/
The generated command (variable vStatement) looks like this:
"Insert a copy of O_GLCEN/o_glcen@SELLENTW o_jh. "X_PLZ_CD_MERGED_CTIS using select * from X_PLZ_CD_MERGED_CTIS".
When you call this procedure as "exec copyTable ('O_GLCEN', 'o_glcen', 'o_jh', 'X_PLZ_CD_MERGED_CTIS', 'SELLENTW');" the following lifts:
FEHLER in line 1:
ORA-00900: invalid SQL statement
ORA-06512: at "SYSTEMTECHNIK". COPYTABLE", line 20
ORA-06512: at line 1
But when you call the command COPY directly from SQL prompt the statement runs without error.
Is in general not possible to use the dynamic COPY with SQL command? If it is possible does anyone has an idea what I am doing wrong?
Any help will be appreciated...
Rgds
JHI would like to use something like
vStatement: = ' start in f (select * from ' | pSourceTableOwner |) '.' || pTableName | '@' || pDatabaseLink | Insert loop ') in ' | pTargetTableOwner | '.' || pTableName | "f-values; end loop; end; »
immediately run vStatement; -
convert the access query to oracle sql
I'm trying to convert this query MS Access to oracle sql:
Sum (IIf (IsNull ([INV_MTL_MATERIAL_TRANSACTIONS1]! [PRIMARY_QUANTITY]), 0,-[INV_MTL_MATERIAL_TRANSACTIONS1]! [PRIMARY_QUANTITY])) AS PRIMARY_QTY
I tried to convert myself but still no luck. Invalid number of arguments.
Sum (if (NVL (INV. MTL_MATERIAL_TRANSACTIONS1. PRIMARY_QUANTITY), 0,-INV. MTL_MATERIAL_TRANSACTIONS1. PRIMARY_QUANTITY)) AS PRIMARY_QTY
Can someone help me convert this request? Thank you.
The immediate if (IIF) statement said:
If primary_quantity is null return 0 for another return negative primary_quantity.
Since there is no difference at all between 0 and - 0 I would write it as:
sum (nvl (primary_quantity, 0) * - 1).
Change a minute later, never send before thinking.
Because you are just adding up the values obtained, he must not care about NULL values at all as aggregate functions generally ignore nulls, it should just be:
Sum (primary_quantity * - 1).
John
-
Tables created in a stored procedure cannot be used with dynamic SQL? The impact?
There is a thread on the forum which explains how to create tables within a stored procedure (How to create a table in a stored procedure , however, it does create a table as such, but not how to use it (insert, select, update, etc.) the table in the stored procedure.) Looking around and in the light of the tests, it seems that you need to use dynamic SQL statements to execute ddl in a stored procedure in Oracle DB. In addition, it also seems that you cannot use dynamic SQL statements for reuse (insert, select, update, etc.) the table that was created in the stored procedure? Is this really the case?
If this is the case, I am afraid that if tables cannot be 'created and used"in a stored procedure using the dynamic SQL, as is the case with most of the servers of DB dynamic SQL is not a part of the implementation plan and, therefore, is quite expensive (slow). This is the case with Oracle, and if yes what is the performance impact? (Apparently, with Informix, yield loss is about 3 - 4 times, MS SQL - 4 - 5 times and so on).
In summary, tables created within a stored procedure cannot be 'used' with dynamic SQL, and if so, what is the impact of performance as such?
Thank you and best regards,
Amedeo.
Published by: AGF on March 17, 2009 10:51AGF says:
Hi, Frank.Thank you for your response. I understand that the dynamic SQL is required in this context.
Unfortunately, I am yet to discover "that seeks to" using temporary tables inside stored procedures. I'm helping a migration from MySQL to Oracle DB, and this was one of the dilemmas encountered. I'll post what is the attempt, when more.
In Oracle, we use [global temporary Tables | http://www.psoug.org/reference/OLD/gtt.html?PHPSESSID=67b3adaeaf970906c5e037b23ed380c2] aka TWG these tables need only be created once everything like a normal table, but they act differently when they are used. The data inserted in TWG will be visible at the session that inserted data, allowing you to use the table for their own temporary needs while not collide with them of all sessions. The data of the TWG will be automatically deleted (if not deleted programmatically) when a) a commit is issued or b) the session ends according to the parameter that is used during the creation of the TWG. There is no real need in Oracle to create tables dynamically in code.
I noticed that many people say that the "Creation of the tables within a stored procedure" is not a good idea, but nobody seems necessarily explain why? Think you could elaborate a little bit? Would be appreciated.
The main reason is that when you come to compile PL/SQL code on the database, all explicit references to tables in the code must correspond to an existing table, otherwise a djab error will occur. This is necessary so that Oracle can validate the columns that are referenced, the data types of those columns etc.. These compilation controls are an important element to ensure that the compiled code is as error free as possible (there is no accounting for the logic of programmers though ;)).
If you start to create tables dynamically in your PL/SQL code, so any time you want to reference this table you must ensure that you write your SQL queries dynamically too. Once you start doing this, then Oracle will not be able to validate your SQL syntax, check the types of data or SQL logic. This makes your code more difficult to write and harder to debug, because inevitably it contains errors. It also means that for example if you want to write a simple query to get that one out in a variable value (which would take a single line of SQL with static tables), you end up writing a dynamic slider all for her. Very heavy and very messy. You also get the situation in which, if you create tables dynamically in the code, you are also likely to drop tables dynamically in code. If it is a fixed table name, then in an environment multi-user, you get in a mess well when different user sessions are trying to determine if the table exists already or is the last one to use so they can drop etc. What headache! If you create tables with table names, then variable Dynamics not only make you a lot end up creating (and falling) of objects on the database, which can cause an overload on the update of the data dictionary, but how can ensure you that you clean the tables, if your code has an exception any. Indeed, you'll find yourself with redundant tables lying around on your database, may contain sensitive data that should be removed.
With the TWG, you have none of these issues.
Also, what is the impact on the performance of the dynamic SQL statements in Oracle? I read some contrasting opinions, some indicating that it is not a lot of difference between static SQL and SQL dynamic in more recent versions of Oracle DB (Re: why dynamic sql is slower than static sql is this true?)
When the query runs on the database, there will be no difference in performance because it is just a request for enforcement in the SQL engine. Performance problems may occur if your dynamic query is not binding variable in the query correctly (because this would cause difficult analysis of the query rather than sweet), and also the extra time, to dynamically write the query running.
Another risk of dynamic query is SQL injection which may result in a security risk on the database.
Good programming will have little need for the tables of dynamically created dynamically or SQL.
-
Hello gurus,
I have a doubt!
How to get the value of a dynamic sql inside the loop For?
Kind regardsDECLARE lv_v_sql VARCHAR2 (4000); BEGIN lv_v_sql := 'SELECT a FROM' || ' (SELECT 1 AS a FROM DUAL ' || 'UNION ALL ' || 'SELECT 2 AS a FROM DUAL' || ' UNION ALL ' || 'SELECT 3 AS a FROM DUAL ' || ' UNION ALL ' || ' SELECT 4 AS a FROM DUAL' || ' UNION ALL ' || ' SELECT 5 AS a FROM DUAL) ' || ' where a=' || 1; EXECUTE IMMEDIATE lv_v_sql; DBMS_OUTPUT.put_line (lv_v_sql); FOR i IN lv_v_sql LOOP DBMS_OUTPUT.put_line (i); END LOOP; END;
a friend :)Just add IN the clause EXECUTE IMMEDIATE. Example below shows you how to select EXECUTE IMMEDIATE data when it returns a single row and when she returns several lines:
SQL> DECLARE 2 lv_v_sql VARCHAR2 (4000); 3 v_a number; 4 v_a_tbl sys.OdciNumberList; 5 BEGIN 6 lv_v_sql := 7 'SELECT a FROM' 8 || ' (SELECT 1 AS a FROM DUAL ' 9 || 'UNION ALL ' 10 || 'SELECT 2 AS a FROM DUAL' 11 || ' UNION ALL ' 12 || 'SELECT 3 AS a FROM DUAL ' 13 || ' UNION ALL ' 14 || ' SELECT 4 AS a FROM DUAL' 15 || ' UNION ALL ' 16 || ' SELECT 5 AS a FROM DUAL) ' 17 || ' where a=' 18 || 1; 19 EXECUTE IMMEDIATE lv_v_sql 20 INTO v_a; 21 DBMS_OUTPUT.put_line (lv_v_sql); 22 DBMS_OUTPUT.put_line(v_a); 23 lv_v_sql := 24 'SELECT a FROM' 25 || ' (SELECT 1 AS a FROM DUAL ' 26 || 'UNION ALL ' 27 || 'SELECT 2 AS a FROM DUAL' 28 || ' UNION ALL ' 29 || 'SELECT 3 AS a FROM DUAL ' 30 || ' UNION ALL ' 31 || ' SELECT 4 AS a FROM DUAL' 32 || ' UNION ALL ' 33 || ' SELECT 5 AS a FROM DUAL) '; 34 EXECUTE IMMEDIATE lv_v_sql 35 BULK COLLECT 36 INTO v_a_tbl; 37 DBMS_OUTPUT.put_line (lv_v_sql); 38 FOR i IN 1..v_a_tbl.COUNT 39 LOOP 40 DBMS_OUTPUT.put_line(v_a_tbl(i)); 41 END LOOP; 42 END; 43 / SELECT a FROM (SELECT 1 AS a FROM DUAL UNION ALL SELECT 2 AS a FROM DUAL UNION ALL SELECT 3 AS a FROM DUAL UNION ALL SELECT 4 AS a FROM DUAL UNION ALL SELECT 5 AS a FROM DUAL) where a=1 1 SELECT a FROM (SELECT 1 AS a FROM DUAL UNION ALL SELECT 2 AS a FROM DUAL UNION ALL SELECT 3 AS a FROM DUAL UNION ALL SELECT 4 AS a FROM DUAL UNION ALL SELECT 5 AS a FROM DUAL) 1 2 3 4 5 PL/SQL procedure successfully completed.
SY.
-
How to store results of the select query in the tables.
I created a variable varray type and now want to assign some data of output of the select query in pl/SQL, as well as in reports 6i.You are in the wrong forum (this is for problems with the SQL Developer tool). You were the one where you have published first on the right, but not to reuse independent threads as you did.
Kind regards
K. -
Dynamic recovery for the dynamic sql query
Hi all
I want to create a query dynamically and to fetch it in a dynamic cursor record... The structure of the record should be the same as that of the query...
Can you suggest any method to do this.
for example
OPEN < dynamic news > TO < dynamic stmt >;
LOOP
FETCH < dynamic news > < DYNAMIC rec >;
---
END LOOP;
CLOSE < dynamic news >;
How to declare the rec here dynamic? I wouldn't have the columns in the query in advance either.
Thank you
Merz
Published by: merz Sep 12, 2011 17:02
Published by: merz Sep 12, 2011 17:03Merz says:
How to declare the rec here dynamic? I wouldn't have the columns in the query in advance either.
Is not possible. What you describe is called four dynamic sql type. For this type of synamic SQL, you use the DBMS_SQL package.
SY.
-
Dynamic SQL query in the DB adapter
Hello
I want to use the following custom SQL query in the DB adapter:
SELECT EMP_ID, EMP_NAME, EMP_LOCATION FROM EMP WHERE EMP_ID IN (#iNPUT_PARAMETER)
the problem I'm facing is that I don't know at the time of the development that EMP_ID how much will be passed to the process so that I can not use the input parameter specific number. I cannot use it IN the query within which statement I concatenate all the EMP_ID separated by comma and passed under INPUT_PARAMETER, but when running, he read the full concatenated string as a single string rather than identify them as a list of different: with comma separation. could someone help me in this case
Thank you
SunilUse the following query with two parameters. Build the string with delimiter when running and pass this string and delimiter to query... (in this example, the input value would be the same for both Delimiter1 and Delimiter2.)
Select * from EMP WHERE deptno IN (SELECT SUBSTR (STRING_TO_TOKENIZE, DECODE (LEVEL, 1, 1, INSTR (STRING_TO_TOKENIZE, SEPARATOR, 1, LEVEL-1) + 1), INSTR (STRING_TO_TOKENIZE, SEPARATOR, 1, LEVEL)-DECODE (LEVEL, 1, 1, INSTR (STRING_TO_TOKENIZE, SEPARATOR, 1, LEVEL-1) + 1)) FROM (SELECT #StringToTokenizer | #Delimiter1 AS STRING_TO_TOKENIZE, #Delimiter2 AS DELIMITER FROM DUAL) CONNECT BY INSTR (STRING_TO_TOKENIZE SEPARATOR) ((, 1, LEVEL) > 0)
Thank you
-Sreeny -
SQL query to dynamically filter the records-need help
Hello
I have a table with the structure as below
Create table T1
(Number (5) ID,)
Action Varchar2 (20)
)
Here's the table of contents at different points in time and please help me with a query that must dynamically discover the results according to the entries in the table.
First Table contents
1 pending
2 waiting
Result of the query must be
1 pending
2 waiting
After an insert the Table of contents
1 pending
2 waiting
3 ignored
Result
Nothing should be displayed
After an insert the Table of contents
1 pending
2 waiting
3 ignored
4 ignored
Result
Nothing should be displayed
After an insert the Table of contents
1 pending
2 waiting
3 ignored
4 ignored
5 in queue
Result
5 in queue
Thanks in advance!
Best regards
SridharHi, Sridhar,
So you want to show t1 lines that come after the last row with action = "Ignored", which means no output at all during the last row has action = "ignored". (A line with a given id is considered as ' after' a line with a lower id. The line with the highest id is considered the "last" line.)
Is this fair?Here's one way:
SELECT * FROM t1 WHERE id > ( SELECT MAX (id) FROM t1 WHERE action = 'Ignored' ) ;
It's not assume this id is whole consecutive.
If the id is not unique, what results do you want? There is a chance that the above query is already doing if this is not the case, it can probably be changed.
-
Difference between static &; dynamic sql
Hello
It is my first question in OTN.
I have a pl/sql procedure with no insert statements.
Insert into table values...
If I turn all these insert statements in dynamic sql, my procedure will give more effective? (execution)
Please help me.
Thanks in adv
Friend
Hello
8b00c42d-7716-467e-BCEF-c756fd9599e2 wrote:
Hello
It is my first question in OTN.
Welcome to the Forum!
To get the most out of this Forum, see the FAQ in the Forum: Re: 2. How can I ask a question on the forums?
For all performance issues, see also this Forum FAQ page: Re: 3. how to improve the performance of my query? / my query is slow.
I have a pl/sql procedure with no insert statements.
Insert into table values...
If I turn all these insert statements in dynamic sql, my procedure will give more effective? (execution)
Probably not. Dynamic SQL is generally less effective than static SQL, as well as being more difficult to code, debug and maintain.
Is there a reason why you think that the dynamic SQL would be preferable in this case? If so, what is it?
-
Dynamic display of columns in the pivot query
I have a table called STUDENT_SCORE. I need to display the avarage score/month for 2 years and the monthly score until today "month.
Then assume that it is April 2009. The report will look like
Roll_id 2007avg 2008avg Jan09-Mar09 Feb 09
101 80.9 70.9 89.7 90.9 56.8
102 70.9 23.9 87.2 90.0 76.8
I tried a bit, but can't fix the monthly score display dynamically.
DDL/DML is as below
create the table STUDENT_SCORE
(number of roll_id,
date of mth_id,
The partition number);
insert into STUDENT_SCORE values
(101, to_date (January 1, 2006 ', ' dd/mm/yyyy'), 67.5);
insert into STUDENT_SCORE values
(101, to_date (February 1, 2006 ', ' dd/mm/yyyy'), 77.5);
insert into STUDENT_SCORE values
(101, to_date (March 1, 2006 ', ' dd/mm/yyyy'), 87.5).
insert into STUDENT_SCORE values
(101, to_date (April 1, 2006 ', ' dd/mm/yyyy'), 27.5);
insert into STUDENT_SCORE values
(101, to_date (May 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (June 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (July 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (August 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (September 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (October 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (November 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (December 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (January 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (February 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (March 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (April 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (May 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (June 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (July 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (August 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (September 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (October 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (November 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (December 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (1 January 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (February 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (March 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (April 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (May 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (June 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (July 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (August 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (September 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (October 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (November 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (December 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(101, to_date (January 1, 2009 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (January 1, 2006 ', ' dd/mm/yyyy'), 67.5);
insert into STUDENT_SCORE values
(102, to_date (February 1, 2006 ', ' dd/mm/yyyy'), 77.5);
insert into STUDENT_SCORE values
(102, to_date (March 1, 2006 ', ' dd/mm/yyyy'), 87.5).
insert into STUDENT_SCORE values
(102, to_date (April 1, 2006 ', ' dd/mm/yyyy'), 27.5);
insert into STUDENT_SCORE values
(102, to_date (May 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (June 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (July 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (August 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (September 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (October 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (November 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (December 1, 2006 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (January 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (February 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (March 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (April 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (May 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (June 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (July 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (August 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (September 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (October 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (November 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (December 1, 2007 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (1 January 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (February 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (March 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (April 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (May 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (June 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (July 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (August 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (September 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (October 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (November 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (December 1, 2008 ', ' dd/mm/yyyy'), 57.5);
insert into STUDENT_SCORE values
(102, to_date (January 1, 2009 ', ' dd/mm/yyyy'), 57.5);Hello
The script below produces what you want (as far as I can tell, without your desired results).
Student_score_smry subquery Gets the year and monthly averages of student_score.
It is completely static: it always produces 11 monthly columns (from January to November) and the names of columns hardcoded (m01 through m11).
For dynamic column names you need, I used SQL * COLUMN more orders.
To get the variable number of monthly columns you need, SELECT from the main query clause uses a script under (dynamic_month.sql) to only show the correct number (which can be 0).The student_score_wk_smry of subquery retrieves the weekly averages of the student_score_wk.
He, too, is completely static: it always produces 6 weekly columns with names hardcoded (w1 through w6).There are four preliminary motions, that write two scripts under:
Prelimiary C1, C2 and C3 queries write orders of COLUMN for annual, monthly and weekly columns in dynamic_columns.sql
Preliminary motion M written between 0 and 11 items in SELECT-clause in sub-script dynamic_month.sqlThe main script is:
SET FEEDBACK OFF SET LINESIZE 200 SET PAGESIZE 0 SET VERIFY OFF SPOOL dynamic_column.sql -- Preliminary query C1: Columns for last 2 years SELECT 'COLUMN y' || LEVEL || ' HEADING "' || TO_CHAR ( ADD_MONTHS ( &target_month , 12 * (-3 + LEVEL) ) , 'YYYY' ) || 'avg"' FROM dual CONNECT BY LEVEL <= 2 ; -- Preliminary query C2: 11 prior months in this year SELECT 'COLUMN m' || TO_CHAR (LEVEL, 'fm00') || ' HEADING "' || TO_CHAR ( ADD_MONTHS ( TRUNC (&target_month, 'YYYY') , LEVEL - 1 ) , 'MonYY' ) || '"' FROM dual CONNECT BY LEVEL <= 11 ; -- Preliminary query C3: 6 weeks before target_month WITH got_w_num AS ( SELECT SUBSTR (week_desc, 1, 6) AS mon_dd , ROW_NUMBER () OVER ( ORDER BY week_id DESC ) AS w_num FROM week WHERE TO_DATE (week_desc, 'Mon DD, YYYY') < &target_month ) SELECT 'COLUMN w' || TO_CHAR (7 - w_num) || ' HEADING "Week of ' || mon_dd || '"' FROM got_w_num WHERE w_num <= 6 ORDER BY w_num DESC ; SPOOL OFF -- Preliminary Query M: 0-11 months (in SELECT clause) SPOOL dynamic_month.sql SELECT ', m' || TO_CHAR (LEVEL, 'fm00') FROM dual WHERE MONTHS_BETWEEN (&target_month, TRUNC (&target_month, 'YYYY')) >= 1 CONNECT BY LEVEL <= MONTHS_BETWEEN (&target_month, TRUNC (&target_month, 'YYYY')) ; SPOOL OFF -- Restore SQL*Plus features suppressed earlier SET FEEDBACK ON SET LINESIZE 80 SET PAGESIZE 50 -- COLUMN Commands @dynamic_column.sql -- Main Query WITH student_score_smry AS ( SELECT roll_id , AVG (CASE WHEN TRUNC (mth_id, 'YYYY') = TRUNC (ADD_MONTHS (&target_month, -24), 'YYYY') THEN score END) AS y1 , AVG (CASE WHEN TRUNC (mth_id, 'YYYY') = TRUNC (ADD_MONTHS (&target_month, -12), 'YYYY') THEN score END) AS y2 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = TRUNC (&target_month, 'YYYY') THEN score END) AS m01 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 1) THEN score END) AS m02 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 2) THEN score END) AS m03 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 3) THEN score END) AS m04 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 4) THEN score END) AS m05 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 5) THEN score END) AS m06 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 6) THEN score END) AS m07 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 7) THEN score END) AS m08 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 8) THEN score END) AS m09 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 9) THEN score END) AS m10 , AVG (CASE WHEN TRUNC (mth_id, 'MM') = ADD_MONTHS (TRUNC (&target_month, 'YYYY'), 10) THEN score END) AS m11 FROM student_score GROUP BY roll_id ) , got_w_num AS ( SELECT week_id , ROW_NUMBER () OVER ( ORDER BY week_id DESC ) AS w_num FROM week WHERE TO_DATE (week_desc, 'Mon DD, YYYY') < &target_month ) , student_score_wk_smry AS ( SELECT roll_id , AVG (CASE WHEN W_NUM = 6 THEN score END) AS w1 , AVG (CASE WHEN W_NUM = 5 THEN score END) AS w2 , AVG (CASE WHEN W_NUM = 4 THEN score END) AS w3 , AVG (CASE WHEN W_NUM = 3 THEN score END) AS w4 , AVG (CASE WHEN W_NUM = 2 THEN score END) AS w5 , AVG (CASE WHEN W_NUM = 1 THEN score END) AS w6 FROM student_score_wk s JOIN got_w_num w ON s.wk_id = w.week_id WHERE w_num <= 6 GROUP BY roll_id ) SELECT NVL (ss.roll_id, ssw.roll_id) AS roll_id , y1, y2 @dynamic_month.sql , w1, w2, w3, w4, w5, w6 FROM student_score_smry ss FULL OUTER JOIN student_score_wk_smry ssw ON ss.roll_id = ssw.roll_id ORDER BY roll_id ;
Sub-script dynamic_column.sql might look like this:
COLUMN y1 HEADING "2007avg" COLUMN y2 HEADING "2008avg" COLUMN m01 HEADING "Jan09" COLUMN m02 HEADING "Feb09" COLUMN m03 HEADING "Mar09" COLUMN m04 HEADING "Apr09" COLUMN m05 HEADING "May09" COLUMN m06 HEADING "Jun09" COLUMN m07 HEADING "Jul09" COLUMN m08 HEADING "Aug09" COLUMN m09 HEADING "Sep09" COLUMN m10 HEADING "Oct09" COLUMN m11 HEADING "Nov09" COLUMN w1 HEADING "Week of Dec 21" COLUMN w2 HEADING "Week of Dec 28" COLUMN w3 HEADING "Week of Jan 04" COLUMN w4 HEADING "Week of Jan 11" COLUMN w5 HEADING "Week of Jan 18" COLUMN w6 HEADING "Week of Jan 25"
Other sub-script, dynamic_month.sql, might look like this:
, m01 , m02 , m03
-
How to extract the names of columns in dynamic SQL
Hi all
Is it possible to extract all the names of columns in a dynamic query?
In my case according to the user selections that my query will get changed (number of the column, column name and tables that everything can vary).
So now, is it possible to retrieve all the column names of the dynamic query generated?
I am using Oracle 11g (11.2.0.4)
Thank you
Shaz
Maybe you are looking for
-
Unmountable Boot Volume error message
Hello. Monday, I bought Norton Internet Security 2007 and tried to install it. I was reading a word document while I was installing it. I received an error message and was prompted to restart Windows XP. When I tried to reboot Windows XP. I received
-
Windows Easy Transfer password problem
I had problems with my computer then before sending it for repair, I saved all my stuff on an external hard drive. Now I have my computer is back with a new hard drive and would like to transfer the information on the external hard drive on my comput
-
I just installed FIXIT but when I select an item. to run I get the error code 0 x 80040154 Thank you lib
-
How to create new Admin id when the current administrator id is corrupted - Vista
My id admin does not load. Error is the user profile Service service can not... (I forget the rest). No administrator ID exists so I can connect to my computer with this id, but can't do much except run the existing software. Is it possible to bypas
-
some seem to got my account and sent by email to all my contacts / I need to have it stop
soimeone is currently using my accountant and I need this piracy stop immediately. I don't know how long it goes, but I need to have stop