Dynamic Column Names using Refcursors
Hi,
I have a stored procedure which returns a refcursor. The refcursor contains a SQL query in which the column names and number of columns vary dynamically based on the date parameters passed.
"My objective is to return certain XYZ details of employees for a certain month range."
For ex: For the month of Aug-2011, the column names would be '1-AUG-11' to '31-AUG-11 and for Feb-2011 '1-FEB-11' to '28-FEB-11'
My issue is, when I execute the refcursor query using "EXEC", my column names/headings are preserved.
FIELD NAMES: EMPLOYEE_CODE XYZ_TYPE *1-AUG-11* *2-AUG-11* ... *31-AUG-11*
DATA: EMPCODE_Z TYPE1 VALUE_1 VALUE_1 ... VALUE_31
Whereas when I fetch the refcursor into a collection of nested table and display, my column names are lost.
DATA: EMPCODE_Z TYPE1 VALUE_1 VALUE_1 ... VALUE_31
Is there a way where I can preserve the column names from the refcursor after fetching into pl/sql collections?
Any help would be highly appreciated.
Thank you.
Edited by: 867622 on Nov 11, 2011 4:38 PM
867622 wrote:
If not dynamic SQL, how can the number of columns be altered based on the input parameters?Cannot. A dynamic SQL projection means dynamic SQL (there's an exception to this, and despite interesting is not relevant to 99.99% of problems dealing with dynamic SQL projections).
You can however still use a dynamic projection and wrap that into a user defined type interface.
Here's the basic approach:
// create a user define type that will provide the wrapper for the SQL projection
create or replace type TString as table of varchar2(4000);
// build dynamic SQL projections via this type, e.g.
select
TStrings( object_id, object_name, created )
from user_objects
select
TStrings( emp_id, dept_id, salary, commission )
from employeesDespite the SQL cursors being different and the columns and number of columns being selected different, the SQL projection of both are the same. The Count method tells you the number of columns in the projection. Referencing an applicable column is simply done by using the column's sequential number in the projection.
You also do not have to use a collection or varchar2 as the wrapper type - you can create complex user objects and use the collection type for that, as the SQL projection.
Another alternative is converting the ref cursor into a DBMS_SQL cursor and using the latter's describe interface to dynamically determine the structure of the SQL projection and fetching the column values from it. But 11gr1 or later is needed for doing this.
Similar Messages
-
Im getting an error when running a procedure that includes this code.
I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql
DECLARE @retval AS DECIMAL(12,2)
DECLARE @MonthVal VARCHAR(20), @SpreadKeyVal INT
DECLARE @sqlcmd AS NVARCHAR(150)
DECLARE @paramdef NVARCHAR(150)
SET @MonthVal = 'Month' + CAST(@MonthNumber AS VARCHAR(2) );
SET @SpreadKeyVal = @SpreadKey; --CAST(@SpreadKey AS VARCHAR(10) );
SET @sqlcmd = N' SELECT @retvalout = @MonthVal FROM dbo.CourseSpread WHERE CourseSpreadId = @SpreadKeyVal';
SET @paramdef = N'@MonthVal VARCHAR(20), @SpreadKeyVal INT, @retvalout DECIMAL(12,2) OUTPUT'
--default
SET @retval = 0.0;
EXECUTE sys.sp_executesql @sqlcmd,@paramdef, @MonthVal = 'Month4',@SpreadKeyVal = 1, @retvalout = @retval OUTPUT;
SELECT @retval
DECLARE @return_value DECIMAL(12,2)
EXEC @return_value = [dbo].[GetSpreadValueByMonthNumber]
@SpreadKey = 1,
@MonthNumber = 4
SELECT 'Return Value' = @return_value
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for:
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
>> I need to select from a dynamic column name and save the result in a variable, but seem to be having trouble with the values being fed to sp_executesql <<
This is so very, very wrong! A column is an attribute of an entity. The idea that you are so screwed up that you have no idea if you want
the shoe size, the phone number or something else at run time of this entity.
In Software Engineering we have a principle called cohesion that says a model should do one and only one task, have one and only one entry point, and one and only one exit point.
Hey, on a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, your mindset is that level of sillyity and absurdity.
Do you know that SQL is a declarative language? This family of languages does not use local variables!
Now think about “month_val” and what it means. A month is a temporal unit of measurement, so this is as silly as saying “liter_val” in your code. Why did you use “sp_” on a procedure? It has special meaning in T-SQL.
Think about how silly this is:
SET @month_val = 'Month' + CAST(@month_nbr AS VARCHAR(2));
We do not do display formatting in a query. This is a violation of at the tiered architecture principle. We have a presentation layer. But more than that, the INTERVAL temporal data type is a {year-month} and never just a month. This is fundamental.
We need to see the DDL so we can re-write this mess. Want to fix it or not?
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
How to change recordset bahaviour to accept dynamic column names in the where clause
Hi
im using php-mysql and i make a recordset and i want to make the column names in the where clause to be dynamic like
"select id,name from mytable where $tablename-$myvar";
but when i do this my i break the recordset and it disappear
and when i use variables from advanced recordset it only dynamic for the value of the column not for the column name
and when i write the column name to dynamic as above by hand it truns a red exclamation mark on the server behaviour panel
so i think the only way is to change the recordset behaviour is it? if so How to make it accept dynamic column names?
thanks in advance.As bregent has already explained to you, customizing the recordset code will result in Dreamweaver no longer recognizing the server behavior. This isn't a problem, but it does mean that you need to lay out your dynamic text with the Bindings panel before making any changes. Once you have changed the recordset code, the Bindings panel will no longer recognize the recordset fields.
Using a variable to choose a column name is quite simple, but you need to take some security measures to ensure that the value passed through the query string isn't attempting SQL injection. An effective way of doing this is to create an array of acceptable column names, and check that the value matches.
// create array of acceptable values
$valid = array('column_name1', 'column_name2', 'column_name3');
// if the query string contains an acceptable column name, use it
if (isset($_GET['colname']) && in_array($_GET['colname'], $valid)) {
$col = $GET['colname'];
} else {
// set a default value if the submitted one was invalid
$col = 'column_name1'
You can then use $col directly in the SQL query. -
Hi all,
In my report i need to show one chart view. I'm having one prompt. There the user is asked to select a no. for eg. say 10. and a date eg. 10-JAN-09. So my report should show the data from 10-JAN-09 and go backwards to 10 days. if he selects 5 days then only 5 days of data only need to show from that date. This part is ok. The chart has five sections in it. They are
1) 80-100% of the time period
2) 60-80%
3) 40-60%
4) 20-40%
5) <20%
So the legends should vary according to this.
Suppose if the user selects 10 days then the legend should be,
1) 8-10 days
2) 6-7 days
3) 4-5 days
4) 2-3 days
5) less than 2 days
If user selects 5 means then the legend should be,
1) 5 days
2) 4 days
3) 3 days
4) 2 days
5) 1 day
In the prompt im saving this value in one variable. So all i need to do is to apply aggregation on the variable and place it in the column name. But i dont know where to give it. Please help.
Thanks,
KarthickHi when you dynamically change the table column that will automatically reflect in the chart legend.
please check the following link for dynamically changing column header name
http://oraclebizint.wordpress.com/2008/01/25/oracle-bi-ee-101332-dynamic-column-headers-using-presentation-variables-sets-and-conditional-formatting/ -
Dynamic column name sql?
I need to do a select statement using dynamic column names. Can it be done WITHOUT building a string to execute the sql?
In other words, I want to use a variable name in the SELECT part of a statement.
ThanksProperly done, there shouldn't be a great difference in the performance of static and dynamic SQL. Of course, dynamic SQL is a whole lot more complicated to get right. It's also rather at odds with your requirement that column names get passed in dynamically-- if you don't know what columns you're going to select at compile time, you can't use static SQL.
That said, there are a handful of tricks around using Oracle's built-in XML processing functionality to simulate dynamic SQL. This is almost certainly less efficient than doing dynamic SQL in your case, and a whole lot more complicated, but it's technically not dynamic SQL.
The proper response, though, is almost certainly to either
1) figure out how to design the application so that column names need not be passed in at runtime or
2) use dynamic SQL.
If at all possible, option 1 is generally preferable. While there are situations where dynamic SQL is necessary, those tend to be rather rare.
Justin -
Form with dynamic Column Names
Hello,
I am using "Form with report on table" and I would like to make use of dynamic column names labels that are derived from another table (sql). I am stuck on how to do this, any advice?Hi FourEyes;
Try using this.
Select Col1, Col2, Col3
into :P1_Field1, :P1_Field2, :P1_Field3
from Your_Table
Where (your conditions); -
Cannot use alias for dynamic column name in SELECT statement
Hi,
I want to retrieve values from several tables by using dynamic column & table name as below:
DATA: tbl_name(30) TYPE c VALUE '/bic/tbi_srcsys', " staticly initialized for this example
col_name(30) TYPE c VALUE '/bic/bi_srcsys'. " staticly initialized for this example
SELECT (col_name) INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
The internal table "it_values" does not contain a field named "/bic/bi_srcsys", instead it has another generic field "value" so that the above code can be applied to other tables. I tried to use alias (AS) as below:
SELECT (col_name) AS value INTO CORRESPONDING FIELDS OF TABLE it_values FROM (tbl_name).
But this cannot work. I know that there are other ways to solve this problem, such as by using a single field in SELECT .. ENDSELECT and subsequently appending it to the work area and internal table as below:
SELECT (col_name) INTO (lv_value) FROM (tbl_name).
wa_value-value = lv_value.
APPEND wa_value TO it_values.
ENDSELECT.
Just wonder if there is any other more elegant workaround, because I might have several other fields instead of only one?
Thanks.
Regards,
Joon MengHi Suhas,
thanks for the quick reply.
Sorry that I have not well described the structure of the internal table "it_values". This internal table contains several other fields (key, type, value, etc.).
I guess that the following code
SELECT (col_name) INTO TABLE it_values FROM (tbl_name).
works if the internal table only has one field (value) or the field "value" is in the first position, right?
In this case, I need to fill the "value" field of internal table it_values (ignore the other fields like type, key) with values retrieved from (col_name) of the DDIC table.
Looking forward to your reply.
BR,
Joon Meng -
Dynamic forms using dynamic column names
I have a table with columns such as level_1, level_2, etc.
until level_11 and I have another table with level_id and
description, i.e. for level with id = 1 the description could be
'Crawl.' Id 2 could be 'Walk' etc.
I'm trying to make a checklist so people can mark when
they've done things on the checklist, and then upload those values
to the appropriate tables to store the information so it's all
still there when they go back to check off a new skill.
I can't figure out how to make the column names in the form
dynamic.
I've played around with the formatting and still can't quite
get it. I've tried evaluate(queryname.level_#level_id#),
queryname.label, a bunch of other ones, and I can't seem to get it
to work.
Thanks for the help!Get to know CF's structure / array notation. This comes in
very handy when dealing with queries and form fields.
- Form.myFieldName can also be referenced by
Form["myFieldName"]
- MyQuery.myField can also be referenced by
MyQuery["myField"][rowNumber]
Anything in the above example surrounded by quotation makes
can be made dynamic by just adding in a cf variable surrounded by
pound signs:
get_dealer_completion["level_#level_id#"][1] -
Using dynamic column name in datagrid selectedItems
Hi
I have a datagrid loaded with 2 columns. Allowmultiselect is turned on.
Based on the values selected at run time, I get the corresponding selected column name and its values and shown it on HTML screen.
// grp is datagrid
// dgrcl is a data grid column
// selflds is an array which has 0,1,2,3 values
//selflds[0] = name,selflds[1]=age
for (var l:int=0; l<grp.columnCount; l++)
dgrcl =grp.columns[l];
selflds[l] = dgrcl.dataField;
// srhVals will have only one selected value at any point
// getting the corresponding selected column name and its value
var srhVals:String;
srhVals = String(grp.selectedItem[selflds[1]]);
I am trying to achieve the above selection instead by .selectedItems somthing like this below. By doing like this, I will get all the selected items but not only one. If i try below syntax, i get error. Any one has ideas on how to do.
srhVals = String(grp.selectedItems.selflds[1]);Hi
I got my mistake, there should be no dot operator after selectedItems;
I got a solution - it goes like this:
for(var g:int=0;g<grp.selectedItems.length;g++)
srhVals = srhVals + String(grp.selectedItems[g][selflds[1]]);
So the complete scenario is like this:
Datagrid:
Name Age
a 20
b 30
c 40
d 50
I am selecting b,d in UI. At run time, I get programatically the selecteditem column name as "Name", loop through the selecteditems and store the value in srhVals as b,d.
b,d will be finally shown in UI. -
Dynamic Column Names in Flat File Destination
Hello,
Inside a Data Flow Task, I have an ADO.Net data source which executes a stored procedure that provides results in 5 columns.
The requirement is to have it connect to a flat file destination, such that the column names is dependent on what data was pulled by the data source. There is a variable indicator which identifies the data that was pulled. For example:
If the indicator is 0, then the columns names will be A,B,C,D,E. Otherwise, if the indicator is 1, then column names will be V,W,X,Y,Z.
Any suggestions will be of great help.
AJIf you only have two variations then use a branched execution (based on precedence constraints) and direct it to one DFT or another based on the result returned by the stored procedure.
Otherwise use .net
code to create one package or another dynamically.
PS: I suggest not to bother using SSIS for such a simplistic scenario.
Arthur My Blog -
Dynamic Column name in a Cursor
Hello there,
How can I access data in cursor's field with dynamic fields names, more illustration follows:
My table has columns named as C1,C2,C3 so on
defined a cursor cursor_name on that table,
I need to access the fields by a loop like this:
OPEN cursor_name;
Fetch cursor_name into rec;
for i in 1 .. 10 loop
if rec.ci = 1Then
end if;
end loop
close cursor_name;
where rec,ci represents the name of the cursor fields, so that I loop over them,
how can I implement such an idea,
thanks in advance
regardsThanks Bily, and user10715047,
actually the reason behind the need of such an approach, is as following:
assume that I have table of set of logical conditions, " LOGICAL CONDITIONS" has three columns: ID, Condition_name and the logical_condition, example:
1, c1, x = 1
5, c2, y = 2
10, c3, p = 3 where ID is just a sequence to identify the records from each other "primary key"
assume that I need to provide the possible combination of the result of applying each of the conditions, for example :
if c1 = 1 ,c2= 0 and c3= 1 then my result must be 1 ' This according some predefined rulesso that I created table which contains all the possible logical conditions, ( as the max number of logical conditions are known)
defined as follows : combination( combination_ID, c1, c2, c3, c4, ....cmax, result)
sample record:
combination_ID, c1, c2, c3, .. c max, result
100, 1, 0, 1, ....., 1, 1in the PL/SQL procedure, I would get all the needed combination, into a cursor, then to optimized the code, I need to access the fields ( which is the Ci) in a loop
for i in 1..3 loop
if cursor_rec.ci = 1 then
Action
end if;
end loop;the dynamic name I meant in my first post was this : cursor_rec.ci ,
so that I can access the cursor's fields without the need to name them one by one, as there could be long sequence of conditions to be checked.
hope that I made the idea clearer, Any suggestions, please !
anyway I will give the DBMS_SQL cursors a shot , try if I can use to implement the purpose,
as I know similar dynamical variable names, is available in Java,
Regards, -
Dynamically Pass the Column Name cursor. || Dynamic Column Name
Hi,
I need to dynamically pass the column name based on a Mapping table in a loop ( Right now i have hardcoded stuff )just like using Execute immediate.... Inside the procedure, I have commented as where i hit the problem.
Thanks for all of your time...
Thanks
Muthu
CREATE OR REPLACE PROCEDURE xml_testing_clob AS
doc xmldom.DOMDocument;
main_node xmldom.DOMNode;
root_node xmldom.DOMNode;
user_node xmldom.DOMNode; item_node xmldom.DOMNode;
root_elmt xmldom.DOMElement;
item_elmt xmldom.DOMElement;
item_text xmldom.DOMText;
item_test xmldom.DOMText;
nodelist xmldom.DOMNodeList;
sub_variable varchar2(4000);
x varchar2(200);
y varchar2(200);
sub_var varchar2(4000);
CURSOR get_users IS
SELECT FIRST_NAME,LAST_NAME,ROWNUM FROM USER_INFO_TBL WHERE WEIN_NUMBER = '1234' ;
CURSOR get_cdisc_name IS
select CTS_COL_NAME,CDISC_NAME from CTS2CDISC_DICTIONARY where CTS_TABLE_NAME = 'USER_INFO_TBL';
BEGIN
-- get document
doc := xmldom.newDOMDocument;
doc := xmldom.NewDomDocument;
xmldom.setVersion(doc, '1.0');
xmldom.setStandalone(doc, 'no');
xmldom.setCharSet(doc, 'ISO-8859-1');
-- create root element main_node := xmldom.makeNode(doc);
root_elmt := xmldom.createElement(doc,'AdminData');
root_node := xmldom.appendChild(main_node,xmldom.makeNode(root_elmt));
FOR get_users_rec IN get_users LOOP
item_elmt := xmldom.createElement(doc,'User');
xmldom.setAttribute(item_elmt,'OID' , get_users_rec.rownum);
user_node := xmldom.appendChild(root_node,xmldom.makeNode(item_elmt));
FOR cv_get_cdisc_name IN get_cdisc_name LOOP
EXIT WHEN get_cdisc_name%NOTFOUND;
sub_var := cv_get_cdisc_name.cts_col_name;
sub_variable := 'get_users_rec.';
sub_variable := 'get_users_rec.'||cv_get_cdisc_name.cts_col_name;
x := sub_variable;
dbms_output.put_line(x); -------------- Here i just see the literal string
y := get_users_rec.FIRST_NAME;
dbms_output.put_line(y); -------------- Here i just see actual value ( data )
item_elmt := xmldom.createElement(doc,cv_get_cdisc_name.cdisc_name);
item_node := xmldom.appendChild(user_node,xmldom.makeNode(item_elmt));
item_text := xmldom.createTextNode(doc,x ); ---- This is the place i am hitting with an error .
If i use variable X then i am able to see only the literal
string in the output. BUT if i put cursor name.coulmname,
then the resumt (XML) is fine.I wanted acheive this
dynamically just like execute Immediate
item_node := xmldom.appendChild( item_node , xmldom.makeNode(item_text));
END LOOP;
END LOOP;
-- write document to file using default character set from database
xmldom.WRITETOCLOB(doc,);
xmldom.writeToFile(doc, 'c:\ash\testing_out.xml');
-- free resources
xmldom.freeDocument(doc);
END;
+++++++++++++++++++++++++++++++++++ XML OUTPUT +++++++++++++++++++++++++++++++++++++++++
<?xml version="1.0" ?>
- <AdminData>
- <User OID="1">
<FirstName>get_users_rec.FIRST_NAME</FirstName>
<LastName>get_users_rec.LAST_NAME</LastName> </User>
- <User OID="2">
<FirstName>get_users_rec.FIRST_NAME</FirstName>
<LastName>get_users_rec.LAST_NAME</LastName>
</User>
- <User OID="3">
<FirstName>get_users_rec.FIRST_NAME</FirstName>
<LastName>get_users_rec.LAST_NAME</LastName>
</User>
- <User OID="4">
<FirstName>get_users_rec.FIRST_NAME</FirstName>
<LastName>get_users_rec.LAST_NAME</LastName>
</User>
- <User OID="5">
<FirstName>get_users_rec.FIRST_NAME</FirstName>
<LastName>get_users_rec.LAST_NAME</LastName>
</User>
++++++++++++++++++++++++++++++++++++++++++++++++++++ MAPPING TABLE DETAILS +++++++++++++++++
CTS_COL_NAME CDISC_NAME CTS_TABLE_NAME XML_TAG -----------> Column Name
FIRST_NAME FirstName USER_INFO_TBL Element -----------> Records
LAST_NAME LastName USER_INFO_TBL Element -----------> RecordsMy scenario is little different, let me explain:
My columns will remain same but values changes (based on column formula) according to the selected prompt value
If I select 'Oct' from prompt then
Curr will contain data for 'Oct' only
Next1 will contain data for 'Nov' only
Next2 will contain data for 'Dec' only
Next3 will contain data for 'Jan' of next year only.
Later if I select 'Jul' from prompt then
Curr will contain data for 'Jul' only
Next1 will contain data for 'Aug' only
Next2 will contain data for 'Sep' only
Next3 will contain data for 'Oct' only.
I don't have different columns for each months but the columns are capable to reflect data for any month.
So, how can I reflect the column name as month name for which that contains data.
Regards,
S Anand -
Dynamic column name with SELECT INTO
I am trying to build a function that derives a pay amount from a set of business rules. There are about 40 columns that hold various pay amounts and their column names are variations of 4 indicators (day shift, vs night shift, etc.) that I have to dynamically look up, ie here is the ID number and a timecard, now figure out which of the 40 fields to look up to get the pay amount.
I can determine from the timecard and employee ID which field to look at, but I'm getting hung up with the syntax needed to construct and execute the statement inside the PL/SQL block. I need to RETURN the pay I extract using the function, and I can create the correct SQL statement, but the EXECUTE IMMEDIATE won't accept the SELECT INTO syntax.
Can someone please suggest a solution? Here is the function:
create or replace FUNCTION FN_GET_PAYRATE(tc in NUMBER, e in NUMBER, pc in VARCHAR2)
RETURN NUMBER
IS
e_id NUMBER;
tc_id NUMBER;
pl_cd VARCHAR2(7);
shft VARCHAR2(2);
lvl VARCHAR2(2);
typ VARCHAR2(2);
e_typ VARCHAR2(4);
proj NUMBER;
hrly VARCHAR2(4);
payrt NUMBER;
var_col VARCHAR2(10);
sql_select VARCHAR2(200);
sql_from VARCHAR2(200);
sql_where VARCHAR2(200);
sql_and1 VARCHAR2(200);
sql_and2 VARCHAR2(200);
sql_and3 VARCHAR2(200);
sql_orderby VARCHAR2(200);
var_sql VARCHAR2(2000);
BEGIN
e_id := e;
tc_id := tc;
pl_cd := pc;
SELECT NVL(SHIFT,'D') INTO shft
FROM TS_TIMECARD_MAIN
WHERE TIMECARD_ID = tc_id;
--DBMS_OUTPUT.PUT_LINE('SHIFT= ' || shft);
SELECT NVL(PAY_LVL, 1), NVL(PAY_TYPE, 'B'), NVL(RTRIM(EMP_TYPE), 'LHD'), NVL(PROJECT, 001)
INTO lvl, typ, e_typ, proj
FROM TS_EMPLOYEES
WHERE EMP_ID = e_id;
--DBMS_OUTPUT.PUT_LINE('Level= ' || lvl);
--DBMS_OUTPUT.PUT_LINE('PAY_TYPE= ' || typ);
--DBMS_OUTPUT.PUT_LINE('EMP_TYPE= ' || e_typ);
--DBMS_OUTPUT.PUT_LINE('PROJECT= ' || proj);
IF e_typ <> 'LHD' THEN
hrly := 'H';
ELSE
hrly := '';
END IF;
IF proj <> 001 THEN
var_col := shft || lvl || typ || hrly;
--DBMS_OUTPUT.PUT_LINE('RATE COLUMN= ' || var_col);
sql_select := 'SELECT NVL(' || var_col || ', .01) INTO payrt';
sql_from := ' FROM TS_PAYRATES';
sql_where := ' WHERE PROJECT_ID = ' || proj;
sql_and1 := ' AND ACTIVE = 1';
sql_and2 := ' AND JOB_TYPE = ' || CHR(39) || e_typ || CHR(39);
sql_and3 := ' AND PILE_ID = ' || CHR(39) || pl_cd || CHR(39);
var_sql := sql_select || sql_from || sql_where || sql_and1 || sql_and2 || sql_and3 || sql_orderby;
DBMS_OUTPUT.PUT_LINE('SQL: ' || var_sql);
EXECUTE IMMEDIATE var_sql;
DBMS_OUTPUT.PUT_LINE('RATE= ' || payrt);
RETURN payrt;
ELSE
DBMS_OUTPUT.PUT_LINE('ERROR');
RETURN 1;
END IF;
END;
I have alternately tried this:
SELECT NVL(var_col,.01) into payrt
FROM TS_PAYRATES
WHERE PROJECT_ID = proj AND ACTIVE = 1
AND JOB_TYPE = CHR(39) || e_typ || CHR(39)
AND PILE_ID = CHR(39) || pl_cd || CHR(39);
as a substitute for the EXECUTE IMMEDIATE block, but I can't seem to use a dynamic substitution for the column name.
Any help would be greatly appreciated.That's the most difficult part - the error messages seem to indicate a problem with the SQL statement in its execution context, because I can take the SQL string by itself and it executes perfectly.
Here are three variations:
SELECT INTO
select fn_get_payrate(21555, 30162, 15) from dual
ERROR at line 1:
ORA-00905: missing keyword
ORA-06512: at "PEOPLENETIF.FN_GET_PAYRATE", line 60
SQL: SELECT NVL(N4P , .01) INTO payrt FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15'
Without SELECT INTO (returns NULL)
SQL> select fn_get_payrate(21555, 30162, 15) from dual;
FN_GET_PAYRATE(21555,30162,15)
SQL: SELECT NVL(N4P , .01) FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15'
RATE=
EXECUTE IMMEDIATE USING
SQL> select fn_get_payrate(21555, 30162, 15) from dual;
select fn_get_payrate(21555, 30162, 15) from dual
ERROR at line 1:
ORA-01006: bind variable does not exist
ORA-06512: at "PEOPLENETIF.FN_GET_PAYRATE", line 61
SQL: SELECT NVL(N4P , .01) FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15' -
Materialized view with dynamic column names !
hello,
i need some help , i'm trying ( i got no where so far :) ) to create a materialized
view that has dynamic field name values , so every time the view is refreshed
the fields are renamed.
i have been asked to create a decade summary view and to assign year values to field names,the years should be table columns ( not rows !? ) and thus i should reflect this fact to the column names.
i know its a wierd request but is there anway to do it ?
i dunno about it at least,
Thanks !...or you could define the materialised view neutrally e.g. with columns like YEAR1, YEAR2 etc.
Then create a dynamically-defined view on top of this view, after it's refreshed, using the relevant years as column names. SELECT year1 AS "1991", year2 AS "1992" etc.
I still don't see how anybody is going to use these views as they won't know what the "year" columns are called.
And if the same materialised view is going to have different sets of data each time it's refreshed i.e. different sets of years, are you re-defining the selection criteria each time? If so, why not just define separate views?
It's a weird world out there... -
Need to return dynamic column names for a function returning nested table
I am having a pl/sql function which is returning a nested table.
For this i have defined an object which is having 4 attributes- 1 number type, 3 varchar2 type -p1,p2,p3.
My function is taking input parameter v1,v2,v3 all of varchar2 type.Inside the function body,i am using these (v1,v2,v3) to filter data from an sql query and i am also
using pivot function in this sql query.
At the end my function is returning the object as defined in the starting .
When i am excuting this function,thru select statement :
select * from table(f1_test('A','B','C'));
i am geting p1,p2,p3 as column name ,which are names used when i had defined object type.Instead i want column name to be dynamic (wotever i am passing in function as
parameter while executing the function ,here A,B,C)
Please help me in geting column names dynamic as passed in input parameter (i.e A,B,C for this case )
Sample code for the problem:
create or replace TYPE obj1 AS OBJECT
( id number(5,0)
,p1 varchar2(10),
,p2 varchar2(10)
,p3 varchar2(10)
create or replace TYPE tt1 AS TABLE OF OBJ1;
create or replace
function f1_test (v1 varchar2,v2 varchar2,v3 varchar2)
return tt1 as
v_return tt1 ;
v_str varchar2(30000);
begin
v_str:='
select
cast(
multiset(
select * from
select
aa.report_id
,cc.name
,e.amount
from
aa,cc,e
where
<join conditions>
and cc.name in ('''||v1||''','''||v2||''','''||v3||''')
pivot (sum (amount) for name in ('''||v1||''' as '||v1||','''||v2||''' as '||v2||','''||v3||''' as '||v3||'))
as tt1)
from
dual';
dbms_output.put_line(v_str);
execute immediate v_str
into
v_return ;
return v_return;
end;
Edited by: 845831 on 20 Mar, 2011 12:15 PMselect id,p1 A,p2 B,p3 C from table(f1_test('A','B','C'));
drop function f1_test;
drop type tt1;
drop type obj1;
create or replace TYPE obj1 AS OBJECT
( id number(5,0)
,p1 varchar2(10)
,p2 varchar2(10)
,p3 varchar2(10)
create or replace TYPE tt1 AS TABLE OF OBJ1;
CREATE OR REPLACE
FUNCTION f1_test(
v1 VARCHAR2,
v2 VARCHAR2,
v3 VARCHAR2)
RETURN tt1
AS
v_return tt1 ;
v_str VARCHAR2(30000);
BEGIN
v_str:='select cast(multiset(select 1,''20'',''30'',''40'' from dual) as tt1) from dual';
dbms_output.put_line(v_str);
EXECUTE immediate v_str INTO v_return ;
RETURN v_return;
END;
/
Maybe you are looking for
-
Removing podcast episodes from iTunes 12 but keeping the files
I want to be able to remove a podcast episode from iTunes 12 but keep the audio file on my computer. This used to be an option, but now I am no longer asked if I want to keep the file. It's just automatically moved to the Trash. I like to archive pod
-
How can I install / test Flash Beta Version on Win 8.1 with IE11?
The Flash of IE can not be uninstalled and updated.
-
Am I better off getting Airport Extreme of Time Capsule
I am looking to upgrade my wireless router and I need a new external Hard drive. I store mainly music and movies and would like to be able to easily them . What is the best way to go?
-
Create and Save a filter BW7.3 IP : session locks up
We are upgrading to 7.3. [ patch 5] on our Dev box at the moment. Love the new ABAP stack functionality for IP. BUT we have an issue I've created my cubes, and an appropriate agg level -> No problem here. Created a filter on the agg level -> no issue
-
Iam using Firefox 12.0 Swedish version. When I use Firefox I have problem with the speed downstreams and upstreams. When I use Internet Explorer 64 bit 7 version 9 I dont have this proplem. Why is it so? Firefox Downstream Upstream ~ 50Mbit/s ~ 0.6Mb