How can i pass sql string in proc as in parameter and use in cursor forloop

Dear Experts ,
Please help me in below code.
create or replace PROCEDURE Sample_Spool_Data (SQLSTRING IN VARCHAR2, FILENAME in VARCHAR2) IS
v_spool_file UTL_FILE.FILE_TYPE ;
SQLSTRING VARCHAR2(1000);
BEGIN
v_spool_file := UTL_FILE.FOPEN('MPLD_DQMT',FILENAME,'w');
UTL_FILE.PUT_LINE(v_spool_file,'Start: '||to_char(sysdate,'dd/mm/yyyy hh:mi s'));
FOR c1_rec in SQLSTRING
LOOP
UTL_FILE.PUT_LINE(v_spool_file,c1_rec.rec);
end loop;
UTL_FILE.PUT_LINE(v_spool_file,'End: '||to_char(sysdate,'dd/mm/yyyy hh:mi s'));
SQL String is having like select col1, col2, col3 from table_name;

Looks like you're tring to write a generic way of outputting the results of a query to a file.
You won't do it the way you're trying to, because your dynamic SQL means that you don't know the resultant columns of the query so that you can output them. To do that you need to use the DBMS_SQL package to describe the query and fetch the returned columns by position e.g.
As sys user:
CREATE OR REPLACE DIRECTORY TEST_DIR AS '\tmp\myfiles'
GRANT READ, WRITE ON DIRECTORY TEST_DIR TO myuser
/As myuser:
CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2
                                     ,p_dir IN VARCHAR2
                                     ,p_header_file IN VARCHAR2
                                     ,p_data_file IN VARCHAR2 := NULL) IS
  v_finaltxt  VARCHAR2(4000);
  v_v_val     VARCHAR2(4000);
  v_n_val     NUMBER;
  v_d_val     DATE;
  v_ret       NUMBER;
  c           NUMBER;
  d           NUMBER;
  col_cnt     INTEGER;
  f           BOOLEAN;
  rec_tab     DBMS_SQL.DESC_TAB;
  col_num     NUMBER;
  v_fh        UTL_FILE.FILE_TYPE;
  v_samefile  BOOLEAN := (NVL(p_data_file,p_header_file) = p_header_file);
BEGIN
  c := DBMS_SQL.OPEN_CURSOR;
  DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
  d := DBMS_SQL.EXECUTE(c);
  DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
  FOR j in 1..col_cnt
  LOOP
    CASE rec_tab(j).col_type
      WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
      WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);
      WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);
    ELSE
      DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);
    END CASE;
  END LOOP;
  -- This part outputs the HEADER
  v_fh := UTL_FILE.FOPEN(upper(p_dir),p_header_file,'w',32767);
  FOR j in 1..col_cnt
  LOOP
    v_finaltxt := ltrim(v_finaltxt||','||lower(rec_tab(j).col_name),',');
  END LOOP;
  --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
  UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
  IF NOT v_samefile THEN
    UTL_FILE.FCLOSE(v_fh);
  END IF;
  -- This part outputs the DATA
  IF NOT v_samefile THEN
    v_fh := UTL_FILE.FOPEN(upper(p_dir),p_data_file,'w',32767);
  END IF;
  LOOP
    v_ret := DBMS_SQL.FETCH_ROWS(c);
    EXIT WHEN v_ret = 0;
    v_finaltxt := NULL;
    FOR j in 1..col_cnt
    LOOP
      CASE rec_tab(j).col_type
        WHEN 1 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                    v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
        WHEN 2 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                    v_finaltxt := ltrim(v_finaltxt||','||v_n_val,',');
        WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                    v_finaltxt := ltrim(v_finaltxt||','||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'),',');
      ELSE
        v_finaltxt := ltrim(v_finaltxt||',"'||v_v_val||'"',',');
      END CASE;
    END LOOP;
  --  DBMS_OUTPUT.PUT_LINE(v_finaltxt);
    UTL_FILE.PUT_LINE(v_fh, v_finaltxt);
  END LOOP;
  UTL_FILE.FCLOSE(v_fh);
  DBMS_SQL.CLOSE_CURSOR(c);
END;This allows for the header row and the data to be written to seperate files if required.
e.g.
SQL> exec run_query('select * from emp','TEST_DIR','output.txt');
PL/SQL procedure successfully completed.Output.txt file contains:
empno,ename,job,mgr,hiredate,sal,comm,deptno
7369,"SMITH","CLERK",7902,17/12/1980 00:00:00,800,,20
7499,"ALLEN","SALESMAN",7698,20/02/1981 00:00:00,1600,300,30
7521,"WARD","SALESMAN",7698,22/02/1981 00:00:00,1250,500,30
7566,"JONES","MANAGER",7839,02/04/1981 00:00:00,2975,,20
7654,"MARTIN","SALESMAN",7698,28/09/1981 00:00:00,1250,1400,30
7698,"BLAKE","MANAGER",7839,01/05/1981 00:00:00,2850,,30
7782,"CLARK","MANAGER",7839,09/06/1981 00:00:00,2450,,10
7788,"SCOTT","ANALYST",7566,19/04/1987 00:00:00,3000,,20
7839,"KING","PRESIDENT",,17/11/1981 00:00:00,5000,,10
7844,"TURNER","SALESMAN",7698,08/09/1981 00:00:00,1500,0,30
7876,"ADAMS","CLERK",7788,23/05/1987 00:00:00,1100,,20
7900,"JAMES","CLERK",7698,03/12/1981 00:00:00,950,,30
7902,"FORD","ANALYST",7566,03/12/1981 00:00:00,3000,,20
7934,"MILLER","CLERK",7782,23/01/1982 00:00:00,1300,,10The procedure allows for the header and data to go to seperate files if required. Just specifying the "header" filename will put the header and data in the one file.
Adapt to output different datatypes and styles are required.

Similar Messages

  • HT201250 how can i pass information from one mac to another mac by using the time capsule

    how can i pass information from one mac to another mac by using the time capsule

    If you want to transfer files, settings, etc., you must open Migration Assistant (Applications > Utilities) in the Mac that you want to transfer the files and follow the instructions

  • HT3406 how can i pass "could not active iphone" when I want to use an old iphone 4 as ipod?

    I have old iphone 4 like to use as ipod.  How can i pass "could not active iphone", I just want to use it as ipod.
    thnak you.
    Vivo

    Using an iPhone without a wireless service plan

  • How can I pass dynamic value as a user input parameter in discoverer?

    Hi,
    I have a requirement for a discoverer report like this: The report will display only details for Suppliers that have expired (or soon to be) Insurance details. That is the Expiration Date is less than or equal to the day the report is being run plus any days specified in the Number of Days in the Future Parameter.
    The sample code as:
    SELECT s.segment1 vendor_number
    ,s.vendor_name
    ,flv1.meaning classification
    ,pca.certificate_number
    ,pca.certifying_agency
    ,pca.expiration_date
    ,flv2.meaning status
    FROM ap_suppliers s
    ,pos_bus_class_attr pca
    ,fnd_lookup_values flv1
    ,fnd_lookup_values flv2
    WHERE pca.vendor_id = s.vendor_id
    AND flv1.lookup_code = pca.lookup_code
    AND flv1.lookup_type = pca.lookup_type
    AND flv2.lookup_code = pca.class_status
    AND flv2.lookup_type = 'POS_BUS_CLASS_STATUSES'
    AND pca.expiration_date <= trunc(sysdate) + <No. of Days in the Future>
    order by pca.expiration_date asc
    Now the parameter is Number of Days in the Future (Enter the number days in the future to extract the data. This will default to 0).
    Is it possible in discoverer to do so as in query i do that like a condition as pca.expiration_date <= trunc(sysdate) + <No. of Days in the Future>.
    How can I pass <No. of Days in the Future> as a user input parameter in discoverer?
    Please help.

    Hi,
    All you need to do is to create the condition in the discoverer instead of in the query.
    Create a custom folder containing the following sq (note that i removed the condition)l:
    SELECT s.segment1 vendor_number
    ,s.vendor_name
    ,flv1.meaning classification
    ,pca.certificate_number
    ,pca.certifying_agency
    ,pca.expiration_date
    ,flv2.meaning status
    FROM ap_suppliers s
    ,pos_bus_class_attr pca
    ,fnd_lookup_values flv1
    ,fnd_lookup_values flv2
    WHERE pca.vendor_id = s.vendor_id
    AND flv1.lookup_code = pca.lookup_code
    AND flv1.lookup_type = pca.lookup_type
    AND flv2.lookup_code = pca.class_status
    AND flv2.lookup_type = 'POS_BUS_CLASS_STATUSES'
    Then create a discoverer report using this folder using all fields.
    Create a new calculation as (use this exact syntax):
    Sysdate + :No_of_Days_in_the_Future
    Create a new condition:
    pca.expiration_date <= <your calculation>
    To complete it add a sort as you did in the SQL.
    That's it.
    Tamir

  • How can I pass a String by reference in java?

    Hello!
    My question is how to pass a String by reference in java.
    I tried to declare my variable, instead of using "String xxx = "f";", I used "String xxx = new String ("f");" :
    public static void main (String []args)
    String xxx = new String("f");
    StatusEnum result2 = getErrorPointStr(xxx);
         public StatusEnum getErrorPointStr(String text)
              StatusEnum testStatus = StatusEnum.PASS;
              StringBuffer buffer = new StringBuffer();
    buffer.append("123");
              text = buffer.toString();
              return testStatus;
    After calling to getErrorPointStr(String text) function, xxx = "f"
    So it does not work.
    How can I solve this? It is very important, the function will receive String and not something else.
    Thanks!

    Tolls wrote:
    Which is why I said:
    Which is why you only managed to change what 'text' referred to in the methodExcept that's not why. Even if String was mutable, doing text = whatever; would have the same effect; it would change what that variable refers to in the method, but it would not change the object's state.
    I meant that, since there was no way to actually change the data (ie the char[] or whatever) within the object 'text' referred to, the OP was attempting to change what 'text' referred to and hoping it would be reflected outside the method...which we know won't happen as Java is pass-by-value.\Ah, now I see.
    These by-value/by-reference threads tend to get confusing, because usually the person is passing a String, so the immutability of String tends to get in the way and just muddy the waters.

  • How can I pass a String to a mxml?

    I am trying to pass a string to mxml file.
    following are the part of codes:
    var renderPDFForm:RenderPDFForm=new RenderPDFForm();
    mx.core.Container.addChild.addChild(renderPDFForm);
    The RenderPDFForm is actually a mxml file, I want to do something like when creating the instance, a string can be called.
    Since we can't create constructor for mxml file, how I can do it?
    Thanks,

    So within your mxml file for the RenderPDFForm component:
    <mx:Script>
        <![CDATA[
            private var _myData:String;
            public function set myData(str:String):void{
                _myData = str;
          public function get myData():String{
                return _myData;
        ]]>
    </mx:Script>
    Then in your main app:
    <comp:RenderPDFForm myData="My nice string"/>
    where comp is your namespace name.

  • How can i pass array as argument in magento api method calling using sudzc API in iphone Native APP

    0down votefavorite
    I am implementing magento standard api method in native iphone app. I use webservice generated by sudzc. To call method I use:
    [service call:self action:@selector(callHandler:) sessionId:@" " resourcePath:@" " args:@""];
    When I used methods e.g. cart.info or product.info in which I have to pass one parameter; it gives valid response. But when I used method e.g. cart_product.add in which I have to pass an argument as value of array it gives error
    SQLSTATE[42000]: Syntax error or access violation:
        1064 You have an error in your SQL syntax;
        check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
    I have tested in SOAP UI also. There also it gives me same error. But same method works in PHP file. Even I tried by creating same soap request which I created using JavaScript but still it doesn't work.
    Can anyone help me to pass array as a parameter using sudzc api to call magento web services?

    There is an error in your SQL.

  • CR 8.5, how can I pass just the date, when it wantes date and time?

    I have a stored procedure that is passes a date parameter.
    When CR prompts me for the date, it also wants the time.
    Either I have to pass CR the time of get CR to just look at the date.
    When I run the report with a date and time, CR returns no records.
    When I run the SP in a SQL query with just the date, it returns data.
    I'm CR 8.5 and MS SQL Server 2005
    Any advice would be appreciated.
    Thanks
    Kelvin

    You can pass the parameter values as follows for datetime.
    01/31/2008 00:00:00 which will returns the data in the report.
    If you either not interested to pass the time everytime, you can achieve it through Add Command option in the datasource expert and trigeer the SP. (i'm not sure Add Command is available with CR 8.5)
    Hope this helps!!

  • How can i combine a string array with a waveform array and write this to a file.

    I am trying to set my VI up so that I can enter test information (notes to myself) and combine that with the time and date then write this as well as the waveform data from the daq to a spreadsheet file.  I am sure this is a simple task but I am new to LabView so any help would be very appreciated.

    An XML file is not a spreadsheet-formatted file, so that's not likely to help...
    Simply call the Write To Spreadsheet File twice. The first time you wire in a 1D array of strings
    which is your test information. Then, you call it when you're writing out
    your data. Make sure you wire a True constant to the "append" input for
    that function.

  • How can I pass the photos from one iphone to another?

    how can I pass the photos from one iphone to another?

    Use the Beaming feature. See the info at the ? In iPhoto for iOS.

  • How can I pass empty value in URL Parameter

    Hi,
    I am passing different URL parameters to one page, to filter
    the recordset on that page. How can I pass an empty value in the
    URL parameter so that the recordset in unfiltered?
    The URL parameter is based on one field of the database:
    ContentType. So, the link would be to
    default.asp?ContentType=Event
    and then all records that have the ContentType field in the
    DB as Event are displayed. Is it possible to use this system to
    pass an empty parameter so that all records are displayed?
    Thanks
    Ian

    ?ContentType=All
    <% if (ContentType == "All")
    Build recordset w/o filtering
    ASP is rusty, but those are the basics.
    "iandobie" <[email protected]> wrote in
    message
    news:e8im80$q7m$[email protected]..
    > Hi,
    > I am passing different URL parameters to one page, to
    filter the recordset
    > on
    > that page. How can I pass an empty value in the URL
    parameter so that the
    > recordset in unfiltered?
    > The URL parameter is based on one field of the database:
    ContentType. So,
    > the
    > link would be to
    > default.asp?ContentType=Event
    > and then all records that have the ContentType field in
    the DB as Event
    > are
    > displayed. Is it possible to use this system to pass an
    empty parameter so
    > that
    > all records are displayed?
    > Thanks
    > Ian
    >

  • How can I  pass currencies in flatflle

    Dear all,
              How can I pass currencies in flatfile to Local currency.  And I need all the calculation in Work area.  I need sample program.
    With Regards,
    Satish M R

    Try using FM   CONVERT_TO_LOCAL_CURRENCY
    Please see this example below:
    CALL FUNCTION 'CONVERT_TO_LOCAL_CURRENCY'
           EXPORTING
             client            = sy-mandt
             date              = p_date
             foreign_amount    = p_input
             foreign_currency  = p_currency
             local_currency    = 'YOUR_LOC_CURR'
    IMPORTING
             local_amount      = p_output
    EXCEPTIONS
             no_rate_found     = 1
             overflow          = 2
             no_factors_found  = 3
             no_spread_found   = 4
             derived_2_times   = 5
             OTHERS            = 6.
      IF sy-subrc  0.
        p_output = 0.
      ENDIF.
    Regards

  • How can i pass the Input value to the sql file in the korn shell ??

    Hi,
    How can i pass the Input value to the sql file in the korn shell ??
    I have to pass the 4 different values to the sql file and each time i pass the value it has to generate the txt file for that value like wise it has to generate the 4 files at each run.
    can any one help me out.
    Raja

    Can you please more elaberate., perhaps you should more elaberate.
    sqlplus is a program. you start it from the korn shell. when it's finished, processing control returns to the korn shell. the korn shell and sqlplus do not communicate back and forth.
    so "spool the output from .sql file to some txt file from k shell, while passing the input parameters to the sql file from korn shell" makes no sense.

  • How can I pass value from sql query to unix script

    I am new to oracle/unix.
    I want to write a simple script to find max date from a table and then pass date into a variable in a korn shell script.
    sql is select max(date) from table;
    how can I pass that value in unix shell as a variable. Thanks

    I use to code like this.
    Enjoy Scripting.
    cmd.sql
    select sysdate from dual;
    exit
    db.sh
    #! /usr/bin/ksh
    . ~oracle/.orapaths
    dbdate=$(sqlplus -S user/pwd@servicename @cmd.sql)
    echo $dbdate
    Run shell scripts
    ./db.sh
    SYSDATE --------- 19-JAN-07

  • How can i pass the PROPERTY_FALSE  as string

    Hi,
    How can i pass the PROPERTY_FALSE & PROPERTY_TRUE as string to
         Set_Item_Property('MY_BLOCK.MY_ITEM',ENABLED,PROPERTY_FALSE);
    my requirement is to write a procedure like enable_fields(P_PROERTY_VALUE ..) that enable or disable many items based on the value that i pass.
    Set_Item_Property('MY_BLOCK.MY_ITEM',ENABLED,P_PROERTY_VALUE );
    Thanks in advance.

    Infact , property_false and property_true are not strings, They are constants with values 5 and 4 respectively.
    So where ever you want to have property_false, pass 5
    and property_true , pass 4
    But usually we dont follow this method , as the value of the constants may vary from version to version.
    So in your procedure say, pass 1 for enable and 2 for disable
    procedure (................, p_property number) is
    m_set_enable number ;
    Begin
    If p_property = 1 then
       m_Set_enable := property_true;
    else
       m_Set_enable := property_false;
    end if;
    set_item_property('item1',enabled,m_set_enable);
    End;Edited by: Dora on Dec 29, 2009 2:36 PM

Maybe you are looking for

  • Error in Releasing to Accounting for Rebate Credit Memo

    Hi All, I have a requirement to post from a credit memo rebate settlement an A/P posting document rather than an A/R posting document (payment made against vendor rather than customer). I am using the standard SAP user exit EXIT_SAPLV60B_008 to conve

  • SQL syntax error...

    SQL Syntax: select ename||'-'||job from emp Initially, I was using the .Net Framework Data Provider for Oracle and had no problem bringing up the Query Builder in VS 2008. However, when I use the ODP .Net from Oracle, I get an error when bringing up

  • Why cannot I open my subscription to photoshop?

    I cannot open my subscription to Photoshop. I have paid my monthly fee. I cannot reach tech support by phone and I cannot access a "chat" help support. What can I do? This is wasting a lot of my time and really pissing me off!?

  • MPEG Streamclip on Lion?

    Guys, tearing my hair out hear. I need to rip a project from DVD I did a while back. But every time I try to Export the VS file to Quicktime I get the following message "Error: Can't Create The MOV File". I'm using the latest version of Lion on an In

  • Why can't I right click and copy a email attachment in mail 7.0

    I am tryign to jsut copy jpgs from email attachments without having to save them and when i right click in the new mail there is no longer a copy option. Is there anyway to jsut copy straight from mail without saving the file.