on average + get data from another table

Hello..


I have two tables:
user_table: contains (user_id, username)
rating_table: contains (rating_id, side, user_id)


I am trying to create a view of the note for users...
the notice must contain:
the id, user_name, the average of the coast

I created the following script:

Select a.user_id, b.username, AVG (a.rate_value)
rating_bookstore a, user_bookstore b
where a.user_id = b.user_id
A.user_id group;

but I got the following error message:
ORA-00979: not a GROUP BY expression

any help is appreciated...
Kind regards...

10 x 2 wrote:
Hello..

I have two tables:
user_table: contains (user_id, username)
rating_table: contains (rating_id, side, user_id)

I am trying to create a view of the note for users...
the notice must contain:
the id, user_name, the average of the coast

I created the following script:

Select a.user_id, b.username, AVG (a.rate_value)
rating_bookstore a, user_bookstore b
where a.user_id = b.user_id
A.user_id group;

but I got the following error message:
ORA-00979: not a GROUP BY expression

any help is appreciated...
Kind regards...

Select a.user_id, b.username, AVG (a.rate_value)
rating_bookstore a, user_bookstore b
where a.user_id = b.user_id
A.user_id group, b.username;

Tags: Database

Similar Questions

  • How can I insert data from another table into a table containing a timestamp column

    How you insert data from another table in a table if the target table contains a timestamp column. I tried to set the default value of GETDATE() column in the target table, but it does not work.


    I use MS SQL

    Sorry, I managed to get around this by inserting null as the value

  • update of data from another table

    Hi, I would like to help. I Don t know how I can start doing:


    I have a table with a column with numbers (primary key) and I need to create another column with the same values,


    I want to change a table that has only numeric values (PK) to another
    value, so I disable the constraints of linked tables
    then I create another column that I called the "d" column and copy the values
    from column A to column D

    For example.

    TABLE XYZ

    COLUMN A: COLUMN D: (NEW)

    00001 00001
    00002-00002
    00003-00003
    00004 00004


    Can I change the values in column A and D of the column will be kept

    TABLE XYZ
    COLUMN A: COLUMN D:

    00001 99901
    99902 00002
    99903 00003
    99904-00004


    As the tables that must "point" to the column, I change the values with the new numbering

    TABLE ZZZZ

    COLUMN B: (the values of the column before the change)

    00001
    00002
    00003
    00004
    ...

    I want it like this:

    99901
    99902
    99903
    99903
    99904
    ...


    In other words, I find the current value in column D of the XYZ table for the new value that is in column a.



    I appreciate the help! :)

    Try this
    Here you will find a record in test1 for a record for each line of teste2 in teste2 joined the condition t1.numer_documento2 = t2.numero_documento.

    This is called as subquery related Co. What you were doing was under queries that and not to join the top request.

    UPDATE teste2  t2 SET NUMERO_DOCUMENTO =
    (SELECT T1.NUMERO_DOCUMENTO
      FROM teste1 t1
      WHERE t1.numer_documento2 = t2.numero_documento
      and ROWNUM = 1 )
    
    -- "Check/Select your data before you commit "
    

    SS

  • Creation of interface that won't use c $ table while getting data from one table to the other.

    Hello

    That was the question asked in an interview.

    Given the scenario has been that I have two servers say s1 and s2, each containing a database with tables source1 and source2 respectively...

    And I have a target table on server 2 with name target 1.

    Cent were as

    1 can data ufetch target1 source1 without creating table C $? If Yes, how can it be achieved.

    2. how temporary will be created all to get ata in source1 and source2 to target1? Explain the same thing?

    Also I would like to know what is the actual use of the c arrays $? Why they are used.

    I would be very grateful for answers.

    Thank you and best regards,

    Mahesh

    Hello

    Look at these links.

    http://odiexperts.com/why-creating-a-separate-schema-for-temporary-tables-in-ODI/

    Also this

    http://odiexperts.com/direct-load-by-interface-with-no-work-tables/

    Concerning

  • read in select data from another table

    Hello world.

    IM Oracle11GR2 database.

    I m facing the following problem:

    I have 2 tables.

    In the first picture, I have a few articles and 3 of these items then come.

    (A) point Varchar2

    (B) Item Varchar2.

    (C) point digital and this point is the id of a record in the other table.

    If the digital point > 0 then points A and B must be read in the second table

    In the second table, I have 3 Articles.

    (A) the id of the record.

    B & C point are also point varchar2 and must be read in the first table, point C is > 0.

    I'm looking for the way that when I write a normal selection in the first picture he gives me the point B & C of the second table if C point in the first table is > 0.

    I thought to solve this problem with a trigger or something similar.

    Any idea is welcome.

    Regards to everyone.

    You don't need a trigger for this. A simple select statement should do. Something like that? I got your if condition perfectly.

    SELECT CASE WHEN (T1. C > 0) THEN (SELECT T2. B OF THE T2 WHERE T1. C = T2. (A) T1 OTHERWISE. END A,

    BOX WHEN (T1. C > 0) THEN (SELECT T2. C FROM T2 WHERE T1. C = T2. (A) T1 OTHERWISE. B END HAVE B,

    T1. C

    FROM T1;

    Look at the following example. Check if it fills your scenario.

    -BEGINNING OF THE SAMPLE DATA

    WITH T1 AS)

    SELECT 'A' A, 'B' B, 1 C OF DOUBLE UNION ALL

    SELECT 'C', ', 2 DOUBLE UNION ALL

    SELECT 'DF', 'G', THE DOUBLE 0),

    () AS T2

    SELECT 1, 'X' B 'Y' C DOUBLE UNION ALL

    SELECT 2, 'Z', 'BB' OF THE DOUBLE)

    -END OF THE SAMPLE DATA

    SELECT CASE WHEN (T1. C > 0) THEN (SELECT T2. B OF THE T2 WHERE T1. C = T2. (A) T1 OTHERWISE. END A,

    BOX WHEN (T1. C > 0) THEN (SELECT T2. C FROM T2 WHERE T1. C = T2. (A) T1 OTHERWISE. B END HAVE B,

    T1. C

    FROM T1;

    OUTPUT:

    A  B           C

    -- -- ----------

    X Y 1 - since c > 0 A and B values in table 2 are replaced

    Z BB 2 - since c > 0 A and B values in table 2 are replaced

    DF G 0 - since c = 0, there is even value in table 1

    Post edited by: Parth272025

  • Getting data from several tables

    Hello

    I started a few days working with Oracle TopLink, and since yesterday, I came across a problem that I can not find a solution, so I hope that someone will direct me in the right direction with this one... I'm using the tutorial provided by Oracle [http://www.oracle.com/technology/products/ias/toplink/doc/11110/tutorial/index.htm].

    Assuming I want to get the most effective possible , the following data (* only * these data): first_name_of_employee, last_name_of_employee, number_of_phones_of_employee.
    The Employee and phone tables are involved, table phone has an EMP_ID field that points to the field of the employee EMP_ID. How could I get such data for all employees? The first two pieces of data are pretty easy to get, but get one final turned out to be more difficult than I imagined...

    Any help will be most appreciated.

    Thank you
    Vlad

    You can probably use a ReportQuery and Expressions for this query. In TopLink you can do something you can do in JPQL using Expressions, like our support JPQL uses Expressions. To get the number of phones, you can use a count() on the id of the employee's phone with a groupBy to id of the employee. Get back the name and the name can be tricky depending on your database because I think that you can select return values that groupBy, you might try grouping by first and last name as well.

    that is something like:
    The ExpressionBuilder builder = new ExpressionBuilder();
    Query ReportQuery = new ReportQuery (Builder, Employee.class);
    query.addAttribute ("firstName");
    query.addAttribute ("lastName");
    query.addCount (builder.anyOf("phones").get ("id"));
    query.addGrouping ("id");
    query.addGrouping ("firstName");
    query.addGrouping ("lastName");

    ---
    James: http://www.eclipselink.org

  • update of column based on the sum of the data from another table

    I have two tables:

    Table1 (col1, col2, col3, col4, val1, status) Table2 (col1, col2, col3, col4, val2)

    For Table1 and Table2, column (col1, col2, col3, col4) are the primary key of composit.

    Table2 could have duplicated lines, that's why I want to group by (col1, col2, col3, col4) and sum (val2)

    After that, I want to update Table1.val1 with the value of sum (Table1.val2) where Table1.col1 = Table2.col1 and Table1.col2 = Table2.col2 and Table1.col3 = Table2.col3 and Table1.col4 = Table2.col4 and status = 'V '.

    I did something like this:

    UPDATE Table1 SET val1 = (

       

    WHERE Table1.col1 = t_sommevbrute.col1 and Table1.col2 = t_sommevbrute.col2 and Table1.col3 = t_sommevbrute.col3 and Table1.col4 = t_sommevbrute.col4)

    Could someone help me please? Thank you

    merge into table1 t1

    using (select col1, col2, col3, col4, sum (val2) val2

    from table2

    Group

    by col1, col2, col3, col4) t2

    on (t1.col1 = t2.col1 t1.col2 = t2.col2 and t1.col3 = t2.col3 and t1.col4 = t2.col4 and)

    When matched then

    update set t1.val1 = t2.val2;

  • Inserting data from one table to another table

    Hello

    I have the following SQL where I am updating a table by adding new data from another table, but without success.

    INSERT INTO
    () TOP_PROSPECTS
    COMMON_ID
    DATE_ADDED
    REVIEW_RANK
    EVAL_DATE
    PM_ASSIGN
    WHY_NOTES)
    SELECT
    t.COMMON_ID
    t.DATE_ADDED
    t.REVIEW_RANK
    t.EVAL_DATE
    t.PM_ASSIGN
    t.WHY_NOTES
    Of
    TEMP_IVAN_MARY t
    WHERE
    COMMON_ID <>t.COMMON_ID

    Any suggestions?

    Thank you.

    Published by: user13822709 on August 14, 2012 09:14

    Published by: user13822709 on August 14, 2012 09:15

    Is that what you're trying to do with the insert. I think there may be a sign {noformat}<{noformat}{noformat}>{noformat} missing in the where clause. This site eat those, so you need to use the equivalent! = post here.

    If I'm wrong about the missing trader, then it looks like you want to insert rows in temp_ivan_mary that are not already in top_prospects. If Yes, then you need something like:

    insert into top_prospects
       (common_id, date_added, review_rank, eval_date, pm_assign,
        why_notes)
    select t.common_id, t.date_added, t.review_rank, t.eval_date,
           t.pm_assign, t.why_notes
    from temp_ivan_mary t
    where t.common_id not in (select common_id from top_prospects
                              where common_id is not null)
    

    Function index and data available volumnes etc. then a mergr can be more effective. Something like:

    merge into top_prospects p
       using (select common_id, date_added, review_rank, eval_date,
                     pm_assign, why_notes
              from temp_ivan_mary) t
       on (p.common_id = t.common_id)
       when not matched then
          insert (common_id, date_added, review_rank, eval_date, pm_assign,
                  why_notes)
          values (t.common_id, t.date_added, t.review_rank, t.eval_date,
                  t.pm_assign, t.why_notes)
    from temp_ivan_mary t
    

    John

  • Is it possible to see/get the data from the table to a dump file

    I have files dmp generated using expdp on oracle 11 g...

    expdp_schemas_18MAY2013_1.dmp

    expdp_schemas_18MAY2013_2.dmp

    expdp_schemas_18MAY2013_3.dmp

    Can I use a settings file given below to get the data from the table in the file sql or impdp the only option to load the data of table in database.

    VI test1.par

    USERID = "/ as sysdba".

    DIRECTORY = DATA

    dumpfile=expdp_schemas_18MAY2013%S.dmp

    SCHEMAS = USER1, USER2

    LOGFILE = user_dump_data.log

    SQLFILE = user_dump_data. SQL

    and impdp parfile = test1.par.

    No,

    DataPump cannot retrieve a dumpfile data in a flat file.

    Dean

  • How to get data from a database table and insert into a file

    Hello
    I'm new to soa, I want to create an xml with the data from database tables, I'll have the xsd please suggest me how to get the data in the tables and insert in a file
    concerning

    in your bpel process, you can use the db adapter to communicate with the database.
    with this type of adapter, you can use stored procedures, selects, etc to get the data from your database into your bpel workflow.

    When did it call in your bpel to the db adapter process it will return an output_variable with the contents of your table data, represented in a style of xml form.

    After that, you can use the second card (a file synchronization adapter) to write to the content of this variable in output to the file system

  • Getting data from tables msql and e-mailing the result

    Here is some code that I'm eager to collect data from two tables msql and send by email to a user. (This is to remind the user of their user name and password in a weak security situation - that they have submitted their email address)

    I glued some elements of other pages together, hoping it will do what I want.

    At present, it fails with the message

    "You have an error in your SQL syntax. Check the manual for your version of the MySQL server for the right syntax to use near Test "in line 1", after posting $org as requested (as a test)

    I would be grateful if someone can debug this problem, or otherwise advise.

    <? php require_once('.. /.. / Connections/tormented3.php');? >
    <? PHP
    now, the recordset to email a link to the training
    $colname_rstSix = "1";
    If (isset($_GET['email'])) {}
    $colname_rstSix = (get_magic_quotes_gpc())? $_GET ['email']: addslashes($_GET['email']);
    }
    @mysql_select_db ($database_tormented3, $tormented3);
    $query_rstSix = sprintf ("SELECT ck_organisation FROM chk_sixmonth WHERE ck_email = ' %s", $colname_rstSix);
    $rstSix = mysql_query ($query_rstSix, $tormented3) or die (mysql_error ());
    $row_rstSix = mysql_fetch_assoc ($rstSix);
    $totalRows_rstSix = mysql_num_rows ($rstSix);
    Recordset to the end
    $org = $row_rstSix ["ck_organisation"];
    echo $org; temporary test. Yes, it sends a correct text to monitor

    now recordset to the Organization link to access details

    @mysql_select_db ($database_tormented3, $tormented3);
    $query_rstPword = sprintf ("SELECT username, passwords password organization FROM WHERE = ' %s", $org);
    $rstPword = mysql_query ($query_rstPword, $tormented3) or die (mysql_error ());
    $row_rstPword = mysql_fetch_assoc ($rstPword);
    $totalRows_rstPword = mysql_num_rows ($rstPword);

    Start with routine e-mail
    $start = "your information to update access the website of the mental health of Torbay.
    Your host username";// set up the e-mail header
    $username = $row_rstSix ["username"];
    $pword = $row_rstSix ["password"];
    $message. = '$start $username. Your password is $pword\n please update your entries. « ;
    If (mail ($email "Recall information Access",
    $message, "in: . ((" [email protected] \r\n")) { }
    header ('location:http://www.sample.org.uk "") ;// Redirect to the page if the email has been sent successfully
    "exit";
    } else {}
    $error == ' < style p = "color: red;" > an error has occurred, your email could not be sent. Please try again < /p > ';
    }

    ? >

    Thank you very much.

    I assumed that your first successful query because SELECT... ck_organisation your $org echo printed what you expected.

    Isn't the second query SELECT... Organization which is a failure? Have you tried the echo method or die in this query? Or is it the one that displays "the query is empty?

    Try changing the following code snippet and we'll see what happens. I've added a couple more conditions where you can send them to the form. I added also oblique (') around the domain names in the second query, just in case any of those are reserved words in MySQL (I don't get them, but they are available in the MySQL online documentation).

    mysql_select_db($database_tormented3, $tormented3);
    $query_rstSix = sprintf("SELECT ck_organisation FROM chk_sixmonth WHERE ck_email = '%s'", $colname_rstSix);
    $rstSix = mysql_query($query_rstSix, $tormented3) or die(mysql_error());
    $totalRows_rstSix = mysql_num_rows($rstSix);
    if (!$totalRows_rstSix) {
      // no record exists with email $colname_rstSix
      // Alert user and let them try again.
      exit;
    }
    $row_rstSix = mysql_fetch_assoc($rstSix);
    //end recordset
    $org = $row_rstSix['ck_organisation'];
    echo $org; //temporary test. Yes, it does send correct text to monitor
    
    //now recordset to link organisation to access details
    // mysql_select_db($database_tormented3, $tormented3); // not needed. Still selected from above
    $query_rstPword = sprintf("SELECT `organisation`, `username`, `password` FROM `passwords` WHERE `organisation` = '%s'", $org);
    echo "$query_rstPword
    "; $rstPword = mysql_query($query_rstPword, $tormented3) or die(mysql_error()); $totalRows_rstPword = mysql_num_rows($rstPword); if (!$totalRows_rstPword) { // no record in passwords with $org // Decide what you want to do in this situation. // exit; ??? } $row_rstPword = mysql_fetch_assoc($rstPword);

    --
    Mark A. Boyd
    Keep-on-Learnine :-)

  • Migration of data from a table to another table

    have a table1 that includes the existing data in the format.

    ~@!%~X1~@!%~Y1 in three different coulmns

    creates a new empty table and the need to migrate the data above, which is present in 3 different columns in a column in the new table, as shown in the example below.

    table 1 existing data (| separator of columns for formatting)
    ------------------------------------------------------------------------------------------------------------------------------------
    ID name1 | Name2. Name3
    123 ~@!%~X1~@!%~Y1 | ~@!%~X2~@!%~Y2 | ~@!%~X3~@!%~Y3
    234 ~@!%~X4~@!%~Y4 | ~@!%~X5~@!%~Y5 | ~@!%~X6~@!%~Y6
    456 ~@!%~X7~@!%~Y7 | ~@!%~X8~@!%~Y8 |     ~@!%~X9~@!%~Y9


    Table 2, which will initially be empty and after migration, it should look as follows.

    ID name1
    ----------------------------------------------------------------------------------------------------------------------------
    123 ~@!%~X1~@!%~Y1 & & ~@!%~X2~@!%~Y2 & & ~@!%~X2~@!%~Y2
    234 ~@!%~X4~@!%~Y4 & & ~@!%~X5~@!%~Y5 & & ~@!%~X6~@!%~Y6
    456 ~@!%~X7~@!%~Y7 & & ~@!%~X7~@!%~Y7 & & ~@!%~X7~@!%~Y7

    as shown in the example above

    Name1 column has ~@!%~X1~@!%~Y1
    Column name2 has ~@!%~X2~@!%~Y2
    Name3 column has ~@!%~X3~@!%~Y3

    Once the data is migrating from table 1 for id - 123 looks like below, before joining data from 3 tables, I need apopend & & for each for the token I read of the tabl1 of name1 to end ii should be added "& &" also when I read the name2 I add "& &" at the end of the string before the concatination.

    Here's the sample that deals with data for id - 123 with & & (only & & other symbols are part of the data)

    ~@!%~X1~@!%~Y1 & & ~@!%~X2~@!%~Y2 & & ~@!%~X2~@!%~Y2

    need help in writing a note of migate

    Published by: [email protected] on April 2, 2010 15:42

    Hello

    You are looking for something like this

    CREATE TABLE table_new
    AS
       (SELECT id, name1 || '&&' || name2 || '&&' || name3 name1
        FROM table1);
    

    or if you have the table ready

    INSERT INTO table_new
       (SELECT id, name1 || '&&' || name2 || '&&' || name3 name1
        FROM table1);
    

    Thank you

    Alen

  • Populating one table from another table

    Hi Forum...

    I'm trying to populate a table from another table using CFQUERY... I have no problem with the selection of data from the original table, but need help to get the data into the new table. I use MX 6.1 and access as the database server.
    The two arrays have domain names identical to the same place, and I don't want to have to code all the column names in the selection and insert command. for example

    < cfquery name = "GetData" datasource = 'somename' >
    SELECT * FROM AssetTable1 WHERE BarCode = "123456".
    < / cfquery >

    < cfloop query = "GetData" >
    < cfquery name = "InsData" datasource = 'somename' >
    INSERT INTO AssetTable2 (xxxx...)
    VALUES ("#xxxx... #'")
    < / cfquery >
    < / cfloop >

    I hope this makes sense

    Thanks in advance

    Dave

    If your tables are identical structures and their columns are of the same type and position, and both tables are in the same database, then put everything in a single query.


    INSERT INTO AssetTable2
    SELECT *.
    OF AssetTable1
    WHERE bar code = "123456".

    If the columns were in different positions, then you should be listed explicitly in the INSERT and SELECT the parts, but you get the idea.

    INSERT INTO table1 (col1, col2)
    SELECT col1, col2
    FROM table2
    WHERE all that...

    Phil

  • Y510 unable to get data from the camera.

    Hello

    I have a Y510 with Windows Vista 32 bit, 3 GB RAM, only 5 weeks. I get this message when I try to use Veriface, "unable to get data from the camera. The camera may have been disconnected or busy. I reinstalled Vista of the State in which the laptop came, but it does not work. I also updated the bios and install other updates were available. I would appreciate any advice.

    Thank you

    Peter

    I wish it was as easy as press Fn + Esc, I looked through an another Y510 our office and managed to find a process that must be set to Auto, the process is KtmRm. This process cannot be disabled, handicapped, or on a time delay, it must be AUTOMATIC.

  • extract data from a table to a text file

    I need to extract data from a table to a text file, I twist my output is the following...

    bash-3. $00 vi tap3roamercosts_20110915144318.txt
    lines of 'tap3roamercosts_20110915144318.txt' 393948, 23464348 characters
    ^ LAFGTD | N | 2011090203000001 | 13242514000064 | 1. 0 | 20. 41220 | 02-SEVEN.-11. 01-SEPT.-11. 0 | 13244
    755. 64. 70. 0093794428588 | 0093796234547 | 0 | S2 | E | 412200306902634 | 8. 1. 61500 | 16081 |
    | HW | Call to the Roamer. 0 | I have | Roaming billing Inroamer Plan | 1_0_1 | LKA | N_I_Independent
    the time of day. Rate of Roamer SMST systems | AFGTD20110902030000010001013242514000064 |
    |||||||||||||||||||||

    AFGTD | N | 2011090203000001 | 13242612000044 | 1. 0 | 20. 41220 | 02-SEVEN.-11. 01-SEPT.-11. 0 | 13244
    853. 44. 70. 234. 0093793252818 | 0 | S2 | E | 412200303198150 | 8. 1. 61000 | 12403 | HW | -Ro
    bitter call | 0 | I have | Roaming billing Inroamer Plan | 1_0_1 | N_I_Independent time of Da
    There | Rate of Roamer SMST systems | AFGTD20110902030000010001013242612000044 |
    ||||||||

    AFGTD | N | 2011090203000001 | 13242612000047 | 1. 0 | 20. 41220 | 02-SEVEN.-11. 01-SEPT.-11. 0 | 13244
    853. 47. 70. 234. 0093793252818 | 0 | S2 | E | 412200303198150 | 8. 1. 61000 | 12403 | HW | -Ro
    bitter call | 0 | I have | Roaming billing Inroamer Plan | 1_0_1 | N_I_Independent time of Da
    There | Rate of Roamer SMST systems | AFGTD20110902030000010001013242612000047 |
    ||||||||
    .
    .
    .
    .
    .

    Please help me how to format my output each record in simple lines in oracle sqlplus. Here are the settings I used...

    TERMOUT OFF SET;
    SET ECHO OFF;
    SET LINESIZE 100000;
    THE VALUE OF NEWPAGE 0;
    SET SPACE 0;
    SET PAGESIZE 50000;
    SET FEEDBACK OFF;
    SET THE OFF POSITION;
    SET TRIMSPOOL
    SET THE TAB

    And what was wrong with the answers that you have on your previous thread?

    How to extract data in a text file

    Please do not ask the same question again. If there is a problem with the answers provided, then continue on the same thread that tell people what is the problem.

    Saying that, this is another possibility for you...

    As user sys:

    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 the header line and the data to write into files separate if necessary.

    for example

    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,,10
    

    The procedure allows for the header and the data to separate files if necessary. Just by specifying the file name "header" will put the header and the data in a single file.

    Adapt to the exit of styles and different types of data are needed.

Maybe you are looking for