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'

Similar Messages

  • 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 Meng

    Hi 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

  • 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);

  • Dynamic Pivot with Select Into

    I have this Dynamic Pivot which works fine.
    DECLARE @query VARCHAR(4000)
    DECLARE @years VARCHAR(2000)
    SELECT @years = STUFF(( SELECT DISTINCT'],[' + [factor_label]
    FROM [TEMP_lacp_factors]
    ORDER BY '],[' + [factor_label]
    FOR XML PATH('')
    ), 1, 2, '') + ']'
    SET @query =
    'SELECT * FROM
    SELECT [date_],[issue_id],[cusip],[Factor_value],[factor_label]
    FROM [TEMP_lacp_factors]
    )t
    PIVOT (MAX([factor_value]) FOR [factor_label]
    IN ('+@years+')) AS pvt'
    EXECUTE (@query)
    I'm trying to take the results of that and do a SELECT INTO, so I can move the results to another table.  Is this possible?  I didn't find a whole lot online.
    The error that I'm getting is this.
    Caused by: Column name or number of supplied values does not match table definition.
    How can I do this?  Is it even possible?
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Sure, you can create a table with SELECT INTO, but it cannot be a #temptable. Well, it can be a #temptable, but it will disappear as soon as you exit the scope it was created it, that is the dynamic SQL.
    The question is only, what would you do with this table later? Since you don't know the column names, about all work will have to be done through dynamic SQL.
    A dynamic pivot is a non-relational operation. A SELECT statement produces a table, and a table describes a distinct entity, of which the column are distinct and well-defined attributes. Something which your dynamic pivot does not adhere to.
    There is only one thing you can do with your dynamic pivot: returning the data to the client. I don't know what you want to do with that table, but probably you should do that manipulation before the dynamic pivot, because as I said: that is always your
    last step.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Saving result from sp_executesql into a variable and using dynamic column name - getting error "Error converting data type varchar to numeric"

    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

  • 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...

  • 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.

  • 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.
    Thanks

    Properly 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

  • Item value as column name in select

    Hi,
    I have a problem with selecting the columns in the query using items. For example: I have a query:
    select column_a from table; or select column_b from table;
    and I want to do something like this:
    - any item in which I choose the column name
    - query: select column_from_item from tale
    Is it possible?
    My apex version: 4.0.2.00.07
    My oracle db version: oracle 11g

    Unfortunately, it does not work. For example:
    I have a table book (title, themes ...), which is eight rows. When I create a static list of items containing the column names (display name and returns the name) and a report based on select according to your design(select :P5_select from table;), you get eight records in the name of the column.
    item: select list -> static list -> display value: Title, return value: Title, name: P1_title
    select :P1_title from books;
    result which i get:
    Title
    Title
    Title
    Title

  • Concat to retrieve column name in select

    This is basically what I am trying to do:
    SELECT 'LY_'&#0124; &#0124;to_char(sysdate,'MON')&#0124; &#0124;'SALES' FROM TERR_ACCT_SUM
    Except, instead of returning "LY_OCTSALES", I would like to select the rows in the column LY_OCTSALES. How can I "create" the column name to select?

    Not sure if your question was meant using SQL*PLUS or java code.
    If you want to use JDBC you could create SQL statements in a String variable and pass it to the executeQuery() method in the Statement object .
    If you are using BC4J if you want you could create Dynamic View Objects based on SQL statments created at the run time.
    raghu

  • Dynamic queue name with JMS Queue XML?

    Hi,
    Is it possible to use dynamic queue name with JMS Queue XML?
    I tried using a variable in the JNDI URL, and supply the value in a package. I specified the following in the JNDI URL in the Topology:
    e.g.
    <JMS_RESOURCE>?d=<DTD_FILE>&s=<SCHEMA>&JMS_DESTINATION=#PROJECT_NAME.dest_var
    I declared and set the variable in a package, then tried to load data from the above data server to database. But executing this package gave me the following error:
    7000 : null : java.sql.SQLException: javax.jms.JMSException: Cannot find the target in JNDI (#PROJECT_NAME.dest_var)
    java.sql.SQLException: javax.jms.JMSException: Cannot find the target in JNDI (#PROJECT_NAME.dest_var)
         at com.sunopsis.jdbc.driver.bg.executeQuery(bg.java)
         at com.sunopsis.jdbc.driver.bh.executeQuery(bh.java)
         at com.sunopsis.jdbc.driver.l.f(l.java)
         at com.sunopsis.jdbc.driver.l.executeUpdate(l.java)
         at com.sunopsis.sql.SnpsQuery.executeUpdate(SnpsQuery.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.execSrcOrders(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTaskTrt(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSqlC.treatTaskTrt(SnpSessTaskSqlC.java)
         at com.sunopsis.dwg.dbobj.SnpSessTaskSql.treatTask(SnpSessTaskSql.java)
         at com.sunopsis.dwg.dbobj.SnpSessStep.treatSessStep(SnpSessStep.java)
         at com.sunopsis.dwg.dbobj.SnpSession.treatSession(SnpSession.java)
         at com.sunopsis.dwg.cmd.DwgCommandScenario.treatCommand(DwgCommandScenario.java)
         at com.sunopsis.dwg.cmd.DwgCommandBase.execute(DwgCommandBase.java)
         at com.sunopsis.dwg.cmd.e.i(e.java)
         at com.sunopsis.dwg.cmd.g.y(g.java)
         at com.sunopsis.dwg.cmd.e.run(e.java)
         at java.lang.Thread.run(Unknown Source)
    Am I doing it wrongly?
    Thanks!

    hi,
    as it's not in Adapter-Specific Message Properties
    http://help.sap.com/saphelp_nw04/helpdata/en/10/b1b4c8575a6e47954ad63438d303e4/content.htm
    looks like you cannot do it with jms adapter in standard
    use proxy or your own adapter instead
    Regards,
    michal
    <a href="/people/michal.krawczyk2/blog/2005/06/28/xipi-faq-frequently-asked-questions"><b>XI / PI FAQ - Frequently Asked Questions</b></a>

  • How to remove column name in select clause

    Hello Guys,
    I just want to remove a column name in select clause. Because, I don't want to write all column names. I hope I express myself.
    In other words, I want the following.
    Select   * - unwanted_column  from table;
    instead of this
    Select col1, col2, col3, col4, ........ col 10000 from table;

    Hi,
    Sorry, there's nothing in SQL that means "all columns *except* ...". As the others have said, the only way to get those results in SQL is to list all the columns you do want.
    Your front end may have some feature that allows you to hide a specific column. For example, in SQL*Plus, you can use <tt> COLUMN ... NOPRINT </tt> , like this:
    COLUMN      dname     NOPRINT
    SELECT       *
    FROM       scott.dept
    ORDER BY  dname
    ;Output:
    `   DEPTNO LOC
            10 NEW YORK
            40 BOSTON
            20 DALLAS
            30 CHICAGOThere is a column called dname in the scott.dept table; the query above actually uses it. But, because of the COLUMN command, SQL*Plus won't display that column.
    Edited by: Frank Kulash on Feb 26, 2013 10:10 AM
    Changed scott.dept example.

  • Lookup column names with Power Query

    Hi,
    before I go ahead and change source files, I was wondering if I can use Power Query to get a model with the following data. To simplify the example, I have the following dataset in an Excel sheet:
    In another Excel sheet, the column names are defined, for example:
    What would like to have in Power Query is one table with the column names from the second screenshot in column B. Is there a way to link these two tables together in Power Query in order to use these names as column headers in the dataset?
    Thanks!
    - If a post answers your question, please click "Mark As Answer" on that post!

    You can filter the list of renames against the list of actual column names with something like
        FilteredColumns = Table.SelectRows(Columns, each List.Contains(Table.ColumnNames(Source), [Name])),
    Again, the working end-to-end:
    let
    Source = Table.FromRows({{"New York", 23, 51, 732}, {"Chicago", 25, 421, 23}, {"Los Angeles", 632, 22, 423}}, {"City", "Col 1", "Col 2", "Col 3"}),
    Columns = Table.FromRows({{"Col 1", "Column 1"}, {"Col 2", "Column 2"}, {"Col 3", "Column 3"}, {"Col 4", "Column 4"}}, {"Name", "Value"}),
    FilteredColumns = Table.SelectRows(Columns, each List.Contains(Table.ColumnNames(Source), [Name])),
    ColumnsAsRenames = Table.TransformRows(FilteredColumns, Record.FieldValues),
    RenamedColumns = Table.RenameColumns(Source, ColumnsAsRenames)
    in
    RenamedColumns

  • Change column names when selecting from a collection

    Anyone know how to change C001,C002...etc to readable column names when selecting from a collection? Aliases don't work!
    Paul Platt

    Paul,
    Edit the report attributes and change the column headings by selecting the "Custom" radio button first.
    Sergio

  • Difficult to achive the report layout with dynamic column names

    I have a report layout as below.
    So here the column names are dynamic.And each fixed row group has different calculations. I have a date parameter. If I select July 2013, then I need to show data from July 2012 to July 2013 with Columns(Jul-12, Aug-12...Jul-13). How to achive below layout
    with dynamic columns?

    Hi Sarayu_CM,
    According to your description, you want to filter the records of prior year based on only one parameter selection. Right?
    In this scenario, we can create two parameters. The first one is for user to select. The second parameter is based on the first parameter selection. We don't need to specify Available Values for the second parameter, but we should use expression to specify
    Default Values based on the first parameter selection. Use the expression below:
    =DateAdd("m",-12,FormatDateTime(Parameters!param1.Value))
    Then we just need to apply a filter on the matrix/dataset to get the records which the date is between values in these two parameters.
    If you have any question, please feel free to ask.
    Best Regards,
    Simon Hou

Maybe you are looking for