Use variables in a SELECT INTO FROM command

Hi,
How do I use variables within a select into from command? I want to loop through SYS.DBA_TABLES using a cursor and count the number of rows in a
selection of tables an then insert into a cardinality table.
The count of rows will be stored in a variable called CNT, that bit is easy however I need a variable in the FROM clause because that
value changes with every iteration of the cursor.
e.g.
CNT := 0;
TN := "MyTable";
select count(*) into CNT FROM TN;
insert into cardinality (table_name, row_count) values (TN, CNT);
This is Oracle 9i and I need the row counts in a separate table as they are shipped over to a different environment for analysis purposes.
Any ideas?
Regards
Dave
Edited by: Yorky001 on Sep 15, 2010 10:32 AM

Hi,
Thanks for the info, unfortunately I can get neither example to work on this 9i system, could well be pilot error as I only ever get
to do any Oracle about once per year. In the first query I have tried both "user_tables" and SYS.DBA_TABLES, same result.
set serveroutput on size 1000000;
DECLARE
row_count INTEGER;
vstr VARCHAR2(500);
vstr1 VARCHAR2(500);
BEGIN
vstr := 'SELECT count(*) FROM ';
dbms_output.put_line(vstr);
FOR i IN (SELECT table_name FROM user_tables WHERE rownum < 10) LOOP
vstr1 := vstr || i.table_name;
EXECUTE IMMEDIATE vstr1
INTO row_count;
dbms_output.put_line(i.table_name || ':' || row_count);
END LOOP;
END;
This one complains about the execute immediate line.
Error report:
ORA-00933: SQL command not properly ended
ORA-06512: at line 12
00933. 00000 - "SQL command not properly ended"
*Cause:   
*Action:
BEGIN
FOR i IN (select
table_name,
to_number(
extractvalue(
xmltype(
dbms_xmlgen.getxml('select count(*) c from '||table_name))
,'/ROWSET/ROW/C')) count
from user_tables
where rownum<6) LOOP
dbms_output.put_line(i.table_name || ':' || i.count);
END LOOP;
END;
ORA-19206: Invalid value for query or REF CURSOR parameter
ORA-06512: at "SYS.DBMS_XMLGEN", line 121
ORA-06512: at line 1
ORA-06512: at line 2
19206. 00000 - "Invalid value for query or REF CURSOR parameter"
*Cause:    The queryString argument passed to DBMS_XMLGEN.newContext was not a valid query, or REF CURSOR.
*Action:   Rewrite the query so that the queryString argument is a valid query or REF CURSOR.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Select into from 2 tables

    Thanks in advance
    Is it possible do a SELECT INTO from 2 tables, that is (like in Informix)
    declare
    rg_table1    table1%ROWTYPE;
    rg_table2    table2%ROWTYPE;
    BEGIN
                 SELECT A.*, B.* INTO  rg_table1 , rg_table2                           
                       FROM table1 a, table2 B
                            WHERE ....

    no, I don't think so....
    SQL> declare
      2     t1 t%rowtype;
      3     s1 s%rowtype;
      4  begin
      5     select t.*
      6          , s.*
      7       into t1
      8          , s1
      9    from t, s
    10    where rownum = 1;
    11  end;
    12  /
       select t.*
    ERROR at line 5:
    ORA-06550: line 5, column 4:
    PLS-00494: coercion into multiple record targets not supported
    ORA-06550: line 9, column 3:
    PL/SQL: ORA-00904: : invalid identifier
    ORA-06550: line 5, column 4:
    PL/SQL: SQL Statement ignored

  • Using Variables in a select statement through a Database Adapter

    I was wondering how I reference a variable in a select statement through a Database Adapter.
    Ex.
    1. I have a global variable that stores an employee number
    2. I want to select an SSN # from a table based on an employee #
    variable.
    select ssn from emp where ssn = :input_variable - ????
    - how do i reference the variable - I am getting a 'missing IN or OUT parameter error?
    Any advice is much appreciated.
    ~Thanks

    I'm just wondering if anyone knows a work around so that I might be able to store a Table's FIELD name in a variable or an array[] so that I can do a query based on the decision of a loop without having to code 10 IF/ELSE statements.For instance, although the above code will not work, this code, although quite lengthy, does:
    If DataGrid1.SelStartCol = 0 Then
    Adodc1.RecordSource = "Select * from tblReservation order by RES__PUR_DT"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 1 Then
    Adodc1.RecordSource = "Select * from tblReservation order by VENDOR"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 2 Then
    Adodc1.RecordSource = "Select * from tblReservation order by VEN_LOC"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 3 Then
    Adodc1.RecordSource = "Select * from tblReservation order by RES_TYPE"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 4 Then
    Adodc1.RecordSource = "Select * from tblReservation order by RES_FROM_DT"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 5 Then
    Adodc1.RecordSource = "Select * from tblReservation order by RES_TO_DT"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 6 Then
    Adodc1.RecordSource = "Select * from tblReservation order by MISC_ADJ"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 7 Then
    Adodc1.RecordSource = "Select * from tblReservation order by STATE_TAX"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 8 Then
    Adodc1.RecordSource = "Select * from tblReservation order by LOC_CHARGE"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 9 Then
    Adodc1.RecordSource = "Select * from tblReservation order by RES_ID"
    Adodc1.Refresh
    ElseIf DataGrid1.SelStartCol = 10 Then
    Adodc1.RecordSource = "Select * from tblReservation order by RES_OP"
    Adodc1.Refresh
    End If
    Do you see where i'm going with this?
    I simple want to use a variable in the "select * from <Table> Order by <Field>"

  • [php+mysql] how to use variables in a select statement?

    Hi all,
    I'm searching for a way to use a variable in the select
    statement of mysql
    query.
    I have this variable that can contain:
    $var=field_1 field_2 field5
    or
    $var=field3 field4 field8
    so, the variable content is not always the same.
    I would like to filter a table selecting only the columns
    specified by the
    current $var content.
    Is this possible to do something like this?
    $var=field1 field5 field10
    SELECT string_to_array($var)
    FROM mytable
    ORDER BY mysortfield ASC
    Or, is there another way to select columns dynamically?
    Thanks for any suggestion.
    tony

    Hi all,
    I'm searching for a way to use a variable in the select
    statement of mysql
    query.
    I have this variable that can contain:
    $var=field_1 field_2 field5
    or
    $var=field3 field4 field8
    so, the variable content is not always the same.
    I would like to filter a table selecting only the columns
    specified by the
    current $var content.
    Is this possible to do something like this?
    $var=field1 field5 field10
    SELECT string_to_array($var)
    FROM mytable
    ORDER BY mysortfield ASC
    Or, is there another way to select columns dynamically?
    Thanks for any suggestion.
    tony

  • Using variables in the Select statement

    Here is my Select statement:
    Set EmpDynaset = OraDatabase.CreateDynaset("select CU_NAME,CU_CONTACT from CU where CU_Name =" & cnt, 0&)
    What's wrong with this? I'm trying to use the variable cnt. Any help? Thanks, Jeremy

    Here is my Select statement:
    Set EmpDynaset = OraDatabase.CreateDynaset("select CU_NAME,CU_CONTACT from CU where CU_Name =" & cnt, 0&)
    What's wrong with this? I'm trying to use the variable cnt. Any help? Thanks, Jeremy Perhaps using the following:
    ("select CU_NAME,CU_CONTACT from CU where CU_Name = :variable")
    then binding the variable to a value before executing the statement..

  • Index used or not for selecting data from ODS in a start routine

    Dear friends,
    In the start routine of the update rules to a cube, I am reading some data of an ODS in to an internal table .
    The ODS is indexed. But, I am not sure if the index is at all used in the Select statement (that gets the data from ODS to the internal table in the start routine) while loading data to the cube.
    Any help is highly appreciated.
    regards,
    atlaj

    Hi Atlaj
    You can findout this is display execution plan for SQL statement in DB02.
    Goto DB02. and under diagnostic, you find explain. Select that and enter your query. Make sure that everything here is in capital format. Below is a sample query which I have entered.
    SELECT "CRM_SALORG" "SALESORG" FROM "/BI0/QORGUNIT"
    WHERE "SALESORG" = ? AND "OBJVERS" = ? AND "DATETO" >= ?
    AND "DATEFROM" <= ?
    The select parameters should be inside qoutes and in caps and even the from table. Once you enter your query in this format, click on explain. It will show the index scan if the index is present. the output for my query will be something like
    0 SELECT STATEMENT ( Estimated Costs =  1,348E+01 [timerons] )
            1 (COOR) RETURN
                2 (    0) TQ
                    3 (    0) FETCH /BI0/QORGUNIT
                        4 (    0) IXSCAN /BI0/QORGUNIT~Z1
    Where my last statement (line 4) is showing index scan and the name of index read is Z1.
    Hope this helps.
    Please let me know if you have any problems entering the query in the specified format and u get any error.
    Regards
    Sriram

  • Issues With Printer Using drv:///sample.drv/generic.ppd from Command Line

    Hi All,
    I was using generic postscript driver earlier with Mountain Lion. I Created a print queue using "lpadmin -p MYPrintQueue -m drv:///sample.drv/generic.ppd -v socket://<IP>:9100 -E"
    This created a print queue with Generic Postscript Driver.
    Now when i am trying same command with Mavericks, It's Creating a Local Raw Printer. Can anyone tell me where i am going wrong.
    I need command line resolution only.
    I know i can create print queue from cups web interface. There its working fine.
    But i need to use command line only.
    Thanks.

    Hi,
    Would you please try following commands?
    Please don't add quotes on the inf file path: change the driver folder name NC Print Drivers as NCPrintDrivers.
    rundll32 printui.dll PrintUIEntry /if /f C:\Temp\NCPrintDrivers\dellopd_A06\dellopd.inf /r "192.168.10.157"
    Make sure to run the command as admin.
    Let me know if it can work fine.
    Kate Li
    TechNet Community Support

  • How can I use variable name as a prameter value in HOST Command ???

    Hi All,
    How can it possible to use variable value in parameter in HOST command ??
    Following in my code:
    host('rwclient server=reptest report=c:\cust_print.rdf p_1= s_sam_cust_id userid=wh1/wh1@dwh desformat=pdf desty=file desname=c:/temp/'||v_sam_cust_id||'.pdf');
    Regards

    Hello,
    The Syntax of the builtin HOST is :
    SyntaxPROCEDURE HOST
    (system_command_string VARCHAR2);
    PROCEDURE HOST
    (system_command_string VARCHAR2,
    screen_action NUMBER);
    So , you can build the system_command_string as any VARCHAR2
    Example are provided in online help :
    http://www.oracle.com/webapps/online-help/forms/10g/topics/f1_help/builth_m/host.html?tp=true
    Regards

  • SELECT-INTO prepared statement?

    Hi,
    I have a single-row select to execute. I don't know if the multi-row select functionality (ResultSets, etc.) should be used for a single-select.
    Here's from the Oracle JDBC Documentation on a prepared statement with input variables:
    PreparedStatement pstmt =
    conn.prepareStatement ("insert into EMP (EMPNO, ENAME) values (?, ?)");
    pstmt.setInt (1, 1500); // The first ? is for EMPNO
    pstmt.setString (2, "LESLIE"); // The second ? is for ENAME
    pstmt.execute ();
    What I would like to do is have a PreparedStatement for output variables in a SELECT-INTO:
    pstmt= conn.prepareStatement("select max(sal) into ? from emp;");
    but there appears to be no bind variable functionality.
    Callable statements apparently are only for stored procedures.
    Basically, should I just use the multirow select for this?
    Thanks,
    Glen

    pstmt= conn.prepareStatement("select max(sal) into ?
    from emp;");
    but there appears to be no bind variable
    functionality.You might be able to bind this as an output parameter, but it seems like extra work (just getting a ResultSet for "select max(sal) from emp" would be a lot more straight forward).
    >
    Callable statements apparently are only for stored
    procedures.Not really, I execute PL/SQL blocks using prepared statements all the time. Sometimes it's the only way to get the data into a format that JDBC can handle.
    Here's an example:
        /** This is the SQL used to call the API ... */
        public static final String spSQL =  
        "declare " +
            "t_warranty_tbl apps.cib_devo_wrapper.wartbltyp; " +
            "x_warranty_tbl apps.cib_devo_wartbltyp; " +
            "x_return_text VARCHAR2(2000); " +
        "begin " +
            "apps.cib_devo_wrapper.cib_get_warranty_info(" +
                "P_SERIAL_NUMBER => ?,"
                "X_WARRANTY_TBL => t_warranty_tbl," +
                "X_RETURN_TEXT => x_return_text," +
                "x_row_count => ?); " +
            // Convert to a table of objects ...
            "x_warranty_tbl := apps.cib_devo_wrapper.cib_warranty_casttowartbltyp(t_warranty_tbl); " +
            // Get the cursor with order by ...
            "OPEN ? FOR SELECT * FROM TABLE(CAST(x_warranty_tbl AS apps.CIB_DEVO_WarTblTyp)) tbl " +
                "WHERE tbl.entitlementReturnCode != apps.cib_devo_wrapper.g_ent_ret_code_08 " +
                "ORDER BY tbl.INSTALLEDAT_CUSTOMER_NAME, tbl.SITE_NAME, tbl.SITE_ID, " +
                          "tbl.PRODUCT_FAMILY, tbl.PRODUCT_NAME, tbl.SERIAL_NUMBER; " +
           "?:=x_return_text; " +
        "end;";In this example, I declare a few variables, call a stored procedure,
    do some more PL/SQL to reduce the results before I finally bring them back.
    The first placeholder (question mark) is the input serial number, the second one is an output parameter that gives the row count. The third
    question mark is the cursor that contains the data I need, and the fourth is a reference to a status message.
    As you can see, the PL/SQL isn't exclusively stored procedure calls.
    >
    Basically, should I just use the multirow select for
    this?I think you'd need code that looks something like:
    DECLARE
    myCount NUMBER;
    BEGIN
    select max(sal) into myCount
    from emp;
    ? := myCount
    END;Although wrapping the select in a BEGIN..END block may be enough.

  • Cursor did not return data if using variables in the where clause

    ENV: report builder 9.0.4.3.0, DB 10g, OS XP
    table and data ctvctyp:
    ctvctyp_code    ctvctyp_code_pred
       CO               Z1
       FE                   Z1
    FUNCTION get_case_type(case_type VARCHAR2) RETURN VARCHAR2 IS
      cursor  type_cur is
        select ctvctyp_code
        from ctvctyp
        where ctvctyp_code_pred = :P_case_type; -- if use 'Z1', it will return 'CO','FE'
                                                -- but if 'Z1' is passed in as case_type, it returns null.
      temp_type     VARCHAR2(4);
      return_type   VARCHAR2(200);
      counter       NUMBER;
    BEGIN
         return_type := '';
         counter := 0;
         srw.message(20,'in case_type is '||case_type);
         open type_cur;
         LOOP
              FETCH type_cur INTO temp_type;
              EXIT WHEN type_cur%NOTFOUND;
              counter := counter+1;
              if temp_type is NULL then
                   srw.message(20,'temp type is null');
              else
                srw.message(20,temp_type);
              end if;
              if counter = 1 then
                   return_type := ''''||temp_type||'''';
              else
                   return_type := return_type||','''||temp_type||'''';
              end if;     
         END LOOP;
         return return_type;
    END;
    In my p_casetype validation trigger:
    function P_CaseTypeValidTrigger return boolean is
         tempCaseType   VARCHAR2(200);
         return_type    VARCHAR2(200);
    begin
        :P_CASETYPE := 'Z1'
        return_type := get_case_type;   --- I got null returned.
      return (TRUE);
    end;
    But in sqlplus:
    declare a bind variable :P_casetype := 'Z1';
    select get_case_type from dual;
    returns:   'FE','MI'

    cursor type_cur is
    select ctvctyp_code
    from ctvctyp
    where ctvctyp_code_pred = _{color:#0000ff}*:P_case_type;*_{color}Shouldn't be this :p_casetype instead of :p_case_type?

  • "Set-aduser -clear" using variables

    Hello all,
    Is it possible to clear an attribute from a user using variables? For example, this little command works fine:
    get-aduser User31 | set-aduser -clear extensionattribute2, extensionattribute3
    However, I'd like to use this command with variables, like if I didn't know what attributes I wanted to clear beforehand, and could add these attributes to a variable and then pass them to set-aduser:
    $Variables = "extensionattribute2, extensionattribute3"
    get-aduser User31 | set-aduser -clear $Variables
    This command will not work, and I'm not sure if it's possible to use variables with the "-clear" parameter of "set-aduser"?

    Hi,
    You can do that this way:
    $attributes = 'extensionAttribute2','extensionAttribute3'
    Set-ADUser -Identity tester1 -Clear $attributes
    Examples:
    Before:
    Get-ADUser -Identity tester1 -Properties extensionAttribute2,extensionAttribute3 |
    Select SamAccountName,extensionAttribute2,extensionAttribute3
    SamAccountName extensionAttribute2 extensionAttribute3
    tester1 ex2 ex3
    After:
    SamAccountName extensionAttribute2 extensionAttribute3
    tester1
    Don't retire TechNet! -
    (Don't give up yet - 12,950+ strong and growing)

  • Pull selected photos from iPhoto in TimeMachine

    Some time ago a fully backed up MacAir died. It had some major infections so we didn't use TM to load the new machine. we just dragged over the items we needed. Now I want to bring over the iPhoto library but I don't want to lose or replace what is on the new Macair. How do I keep what is on the existing new iPhoto library and bring the old pictures into it?

    No
    As I said
    Restore the old iPhoto library  a different location (desktop for example) and use the paid version of iPhoto Library Manager - http://www.fatcatsoftware.com/iplm/ -  to move the photos you want to the new library
    You could use TM to restore selected photos from the masters folder  of the old library and import those to iPhoto  - but this loses a lot - all edits, metadata changes, etc
    You do not directly access TM backups - you use the TimeMachine application to restore them and hen you can access them
    LN

  • I am struggling to learn  to create queries(using variables)

    Hi all,
    I am struggling to learn  to create queries(using variables)
    I want to learn from basics to all existing technics.
    (eg of each variable types and process types).
    if you have any docs please mail to <REMOVED>.
    thanks,
    BW Cheta

    check these links.
    http://www.sd-solutions.com/documents/SDS_BW_Replacement%20Path%20Variables.html
    http://help.sap.com/saphelp_nw04/helpdata/en/3f/89533e5ff4d064e10000000a114084/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/2c/78a03c1178ad2ce10000000a114084/content.htm
    http://help.sap.com/saphelp_nw04/helpdata/en/af/809528939d5b4fbff7e16a5bdc0d85/content.htm
    http://help.sap.com/search/highlightContent.jsp
    http://help.sap.com/saphelp_nw04s/helpdata/en/e3/e60138fede083de10000009b38f8cf/frameset.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/e3/e60138fede083de10000009b38f8cf/frameset.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/e3/e60138fede083de10000009b38f8cf/frameset.htm
    http://help.sap.com/saphelp_nw04s/helpdata/en/e3/e60138fede083de10000009b38f8cf/frameset.htm
    thanks
    kevin.

  • Using SELECT INTO statement to transfer data from one DB to another?

    Hello,
    I need to move data from an SAP table to another downstream SQL server box without flat file in between. I have set up the DBCON interface, so that my ABAP code on SAP can connect to the remote SQL Server, then I can run INSERT command as Native SQL inside the ABAP.
    However, INSERT has performance problem. The best performer as I can find is SELECT INTO statement. But then I am stuck at how to use SELECT INTO to query my local SAP table and send (via INTO) to remote database. I am not even sure whether I should use Open SQL or Native SQL.
    Any suggestion? BTW, I understand the limitation of Native SQL, but we are OK to use it.
    Thanks!

    It appears that this is some kind of migration project due to the scope of the data contained in the single file? If so whatever you do is like ly to be trow away once the migration of data is completed.
    You have a couple of options:
    1) Get the data extracted from HFM in multiple files instead of one bulk file, broken down by scanario,year & period
    2) Take the single data dump file produced by FDM and manipulate it yourself to get the data in a more usuable format for processing through FDM.
    Option 2 could be achieved via any ETL tool or a custom file parsing script. What may be more attractive to you and allow you to fully leverage your investment in FDM is that you could use the PULL adapter that ships as part of the FDM adapter suite to perform this transformation exercise. The PULL adapter takes a flat file input and allows you to use all the in built functionality of FDM to transform it and output a modified flat file (or series of flat files). You could use it to produce multioload files or a series of files broken down by scenario,year,period.
    Whatever you do I would suggest that break the single data file down into smaller chunks as this will help with the iterative debugging process you will inevitably have to undetake whislt migrating the data to the new application.

  • How to select data from 3rd row of Excel to insert into Sql server table using ssis

    Hi,
    Iam having Excel files with headers in first two rows , i want two skip that two rows and select data from 3rd row to insert into Sql Server table using ssis.3rd row is having column names.

                                                         CUSTOMER DETAILS
                         REGION
    COL1        COL2        COL3       COL4           COL5          COL6          COL7
           COL8          COL9          COL10            COL11      
    1            XXX            yyyy         zzzz
    2            XXX            yyyy        zzzzz
    3           XXX            yyyy          zzzzz
    4          XXX             yyyy          zzzzz
    First two rows having cells merged and with headings in excel , i want two skip the first two rows and select the data from 3rd row and insert into sql server using ssis
    Set range within Excel command as per below
    See
    http://www.joellipman.com/articles/microsoft/sql-server/ssis/646-ssis-skip-rows-in-excel-source-file.html
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

Maybe you are looking for

  • Play Button/Space Bar not working. . .

    Hello. . . I'm having difficulty navigating through clips that are in my timeline. The play button is not working. I've tried trashing my preferences several times, to no avail. . . any help would be greatly appreciated.

  • Query small set of record in a big table.

    Hi, in 11.2.0.2 i've a table with about 2milions of record. I use a query that like: select * FROM DOC WHERE INDENTIF = 1001 AND TRASF = 0; to identify new record in the table (TRASF=0). INDENTIF column contains 5 distinct key and TRASF can be 0,1,2

  • IMovie sound problems once shared

    I make a movie with effects and a soundtrack etc and when previewed all is fine..... HOWEVER.... onced shared/saved to a final file ready for import into iDVD or any other program the sound is fine until playback reaches a point where an effect is ap

  • Lots of bugs in CC 2014.1

    Hi there, its been two days since I downloaded the new version of CC (2014.1) on my iMac. I have discovered many bugs this time. 1.  SVG extracted with PS do not show up in browser, have to re-save them in Illustrator setting the "Interactive" option

  • Show different dropdownlists according to the selected value

    Hi All, I need pop up a different dropdownlist according to the selected item in one dropdownlist. .e.g. if I select state in one dropdownlist, another dropdownlist contains all the states will show up beside it. Any one can help me? Thanks a lot