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

Similar Messages

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

  • 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

  • Alias name for the column name in Prompt

    Hi,
    I have a scenario where I am taking column names into prompt. I have used the following SQL in the SQL results under "Show" option of the Prompt.
    SELECT CASE WHEN 1=0 THEN AGE.AGE ELSE '"Orders"."By OrderDate"' END FROM " Real Time"
    UNION ALL
    SELECT CASE WHEN 1=0 THEN AGE.AGE ELSE '"Orders"."By ShipDate"' END FROM "Real Time"
    My problem here is I am getting the column names into the Prompt as "Orders"."By OrderDate" and "Orders"."By ShipDate", which is not acceptable and readable for mat for the user. Is there any way that I can assign an alias name for the column name such as OrderDate and ShipDate in the above SQL.
    Your quick respose is appreciated.
    Thanks,
    Rama

    hi,
    try an alternative one....in your administrator make new columns with alias to ones you want...so you wiil be able to show whatever you want.
    Otherwise,is it possible to show
    SELECT CASE WHEN 1=0 THEN AGE.AGE ELSE '"Orders"."By OrderDate"' as "xxxxxxxxxxxxx"END FROM " Real Time"
    UNION ALL
    SELECT CASE WHEN 1=0 THEN AGE.AGE ELSE '"Orders"."By ShipDate"' as "yyyyyyyyyyyyyyyy"END FROM "Real Time"
    Ending,you want the data from your columns?or just the name??
    hope i helped...
    http://greekoraclebi.blogspot.com/

  • Using values returned from SQL for Report column names

    I am building reports against our TFS development db.
    One of the reports tracks days spent (Dwell Time) in various status categories (eg: New, Assigned, In Development, Hold, etc) for a given "ticket".
    For a fixed list of values from {Work Item].System_State, I can send the results (days in Assigned) to the column named (Assigned) for each status for each event in the [Work Item History], and then sum them for each ticket as:
    Ticket ID      New          Assigned       InDev       etc
    1230001        2                  0                 0          ...
    1230001        0                  1                 2          ....      
    SUM            2                    1                2         ....            
    However, I have many different Projects, each of which use their own Status names.
    I don't want to duplicate the same basic report, if I can avoid it.
    How can I name and generate this data for the unique Status list for each Project?
    Simplest analog is:  name = First(Fields!Status.Value, "TFSdb")
    and allows value for a column name (category) as: =IIF(Fields!Status.Value = First(Fields!Status.Value, "TFSdb"), Fields!Days.Value, 0)
    However this fails beause:
    1. It only delivers the FIRST status value, and,
    2. I cannot SUM an expression which is itself an aggregate (using First).

    RRapport,
    Is this still an issue?
    Thanks!
    Ed Price, Power BI & SQL Server Customer Program Manager (Blog,
    Small Basic,
    Wiki Ninjas,
    Wiki)
    Answer an interesting question?
    Create a wiki article about it!

  • How to use simple types for table column names ?

    Hi,
    can any one tell how to to use simple types for table column names?
    It is required in internationalizing of webdynpro applications.
    Regards,
    Rajesh

    Hi,
    1: define required column names in <SimpleType>
    2:use the following code to get those values
    3:bind 'text' property of Column headers to context attributes
    4:take a context attribute 'Value' as type of <SimpleType>
    5:set these values to context attributes
    IWDAttributeInfo objAttrInfo=wdContext.getNodeInfo().getAttribute(IPrivate<ViewName>View.IContextElement.VALUE);
    ISimpleTypeModifiable simple=objAttrInfo.getModifiableSimpleType();
    Map m=simple.getEnumerationTexts();
    Collection c=m.values();
    Iterator it=c.iterator();
    if(it.hasNext())
    wdContext.currentContextElement.set<att1>(it.next().toString);
    if(it.hasNext())
    wdContext.currentContextElement.set<att2>(it.next().toString);
    if(it.hasNext())
    wdContext.currentContextElement.set<att3>(it.next().toString);
    Regards
    LakshmiNarayana

  • How to use bind variable value for table name in select statement.

    Hi everyone,
    I am having tough time to use value of bind variable for table name in select statement. I tried &p37_table_name. ,
    :p37_table_name or v('p37_table_name) but none worked.
    Following is the sql for interactive report:
    select * from v('p37_table_name') where key_loc = :P37_KEY_LOC and
    to_char(inspection_dte,'mm/dd/yyyy') = :P37_INSP_DT AND :p37_column_name is not null ;
    I am setting value of p37_table_name in previous page which is atm_state_day_insp.
    Following is error msg:
    "Query cannot be parsed, please check the syntax of your query. (ORA-00933: SQL command not properly ended) "
    Any help would be higly appreciated.
    Raj

    Interestingly enough I always had the same impression that you had to use a function to do this but found out from someone else that all you need to do is change the radio button from Use Query-Specific Column Names and Validate Query to Use Generic Column Names (parse query at runtime only). Apex will substitute your bind variable for you at run-time (something you can't normally do in pl/sql without using dynamic 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.

  • 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

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

  • 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 file for clustered server. Only formatted files on which the cluster resource of the server has a dependency can be used. Either the disk resource containing the file is not present in the cluster group or the cluster resource of the Sql Serve

    Hi
    Windows serv 2012 cluster on sql 2012 cluster with 2 instance. on works fine , Second instanc ewhen i try to creat DB a get this message. 
    Cannot use file  for clustered server. Only formatted files on which the cluster resource of the server has a dependency can be used. Either the disk resource containing the file is not present in the cluster group or the cluster resource of the Sql
    Server does not have a dependency on it.
    CREATE DATABASE failed. Some file names listed could not be created. Check related errors. (Microsoft SQL Server, Error: 5184)
    Any help please
    kam
    KAMEL

    Hi Saurabh
    Exactly I have SQL SERVER 2012
    Failover Clustering   in windows server 2012 with two nodes with
    two instances and exactly I run them in the same server and each instance with
    three drives Backup, Data and log.   
    KAMEL

  • Framemaker uses $filename for short file name, can we edit this to change appearance? We do not want the short file name of long filename to include the .fm extension can this be removed or modified to make this happen?

    Framemaker uses <$filename> for short file name, can we edit this to change appearance? We do not want the short file name of long filename to include the .fm extension can this be removed or modified to make this happen? In compiling our books it would be helpful to not have this extension appear as it then requires us to create extra files without them.

    See: System Variables

  • I cannot use Firefox for over a year now as I get a 404 error message. I have cleaned caches etc, deleted & reinstalled twice & it freezes on the Hulu site.

    I cannot use Firefox for over a year now as I get a 404 error message; it is frozen on the Hulu site.

    Are you using a bookmark or does this also happen if you type the address of the main (home) page of the website?
    Bookmarked pages can become invalid, so you may have to enter the main page and then navigate to the wanted page.
    Clear the cache and remove cookies only from websites that cause problems.
    "Clear the Cache":
    *Firefox > Preferences > Advanced > Network > Cached Web Content: "Clear Now"
    "Remove Cookies" from sites causing problems:
    *Firefox > Preferences > Privacy > "Use custom settings for history" > Cookies: "Show Cookies"

  • Sender file adapter - Can I use *.xml for the file name

    Hi Gurus,
    I have some interfaces where I need to pick the file from a directory. The name of the file will have Data<i>time stamp</i> as the naming convention. Can I use *.xml to pick up my files from this directory?
    The help.sap.com documentation says that we can use this naming convention.
    <b>
    &#9679;      File Name
    Specify the name of the file that you want to process. The name can contain placeholders (*, ? (placeholders for exactly one character)) so that you can select a list of files for processing.
    </b>
    I tried using *.xml for my file name in the communication channel, XI is not picking up this file.
    Please let me know if you have the solution.
    Thanks
    Kalyan

    Murthy,
    Thanks for the reply.
    I am using GuildFTP tool as my FTP server. In this tool, all the permissions were given for the file to pick up.
    The status of the file is good.
    Where in the file adapter configuration I have to select 'Read-only'?
    The file adapter is working perfect with the exact name of the file.
    Thanks
    Kalyan

Maybe you are looking for