Reg: WMSYS.WM_CONCAT or LISTAGG

All,
I am trying to select the column names which start with 'E' in my sql query projection area. For this i have used USER_TAB_COLS with WMSYS.WM_CONCAT / LISTAGG too.
I got the column names, with ',' delimeter, but not able inject this to the sql query. Please help me.
SQL> SELECT WMSYS.WM_CONCAT(column_name)
  2    FROM user_tab_cols
  3    WHERE table_name='EMP'
  4    AND column_name LIKE 'E%';
WMSYS.WM_CONCAT(COLUMN_NAME)
EMPNO,ENAME
SQL> SELECT
  2    (SELECT WMSYS.WM_CONCAT(column_name)
  3    FROM user_tab_cols
  4    WHERE table_name='EMP'
  5    AND COLUMN_NAME LIKE 'E%'
  6    ) a
  7  FROM EMP where rownum<=4;
A
EMPNO,ENAME
ERROR:
ORA-22922: nonexistent LOB value
---LISTAGG
SQL> select (select ListAgg(column_name,',')
  2         WITHIN GROUP(ORDER BY COLUMN_NAME DESC) AS CONCATV
  3  from user_tab_cols
  4    WHERE TABLE_NAME='EMP'
  5    AND COLUMN_NAME LIKE 'E%') a FROM EMP WHERE ROWNUM<=3;
A
ENAME,EMPNO
ENAME,EMPNO
ENAME,EMPNO
Thanks,

The SQL Projection must be defined and known to the SQL Engine during compilation time. So you cant pick a column name dynamically and expect it to return its values.
So you have two options to achieve what do you want.
1. Dynamic SQL
2. XML
Example for Dynamic SQL has already been shown to you. Below is a example for obtaining to the output as XML.
SQL> select * from v$version where rownum = 1;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
SQL> select dbms_xmlgen.getxmltype
  2         (
  3             'select ' || ltrim(sys_connect_by_path(column_name, ','), ',') ||
  4             '  from ' || table_name
  5         ) xml_output
  6    from (
  7            select table_name
  8                 , column_name
  9                 , row_number() over(partition by table_name order by column_name) rno
10              from user_tab_columns
11             where table_name = 'EMP'
12               and column_name like 'E%'
13         )
14   where connect_by_isleaf = 1
15   start
16    with rno = 1
17  connect by rno = prior rno + 1
18     and table_name = prior table_name;
XML_OUTPUT
<ROWSET>
<ROW>
  <EMPNO>7369</EMPNO>
  <ENAME>SMITH</ENAME>
</ROW>
<ROW>
  <EMPNO>7499</EMPNO>
  <ENAME>ALLEN</ENAME>
</ROW>
<ROW>
  <EMPNO>7521</EMPNO>
  <ENAME>WARD</ENAME>
</ROW>
<ROW>
  <EMPNO>7566</EMPNO>
  <ENAME>JONES</ENAME>
</ROW>
<ROW>
  <EMPNO>7654</EMPNO>
  <ENAME>MARTIN</ENAME>
</ROW>
<ROW>
  <EMPNO>7698</EMPNO>
  <ENAME>BLAKE</ENAME>
</ROW>
<ROW>
  <EMPNO>7782</EMPNO>
  <ENAME>CLARK</ENAME>
</ROW>
<ROW>
  <EMPNO>7788</EMPNO>
  <ENAME>SCOTT</ENAME>
</ROW>
<ROW>
  <EMPNO>7839</EMPNO>
  <ENAME>KING</ENAME>
</ROW>
<ROW>
  <EMPNO>7844</EMPNO>
  <ENAME>TURNER</ENAME>
</ROW>
<ROW>
  <EMPNO>7876</EMPNO>
  <ENAME>ADAMS</ENAME>
</ROW>
</ROWSET>
SQL>
My version of oracle does not support LISTAGG. So i have used SYS_CONNECT_BY_PATH. But you can use LISTAGG to achieve the same.

Similar Messages

  • DISTINCT not working with  wmsys.wm_concat

    Need help on this :
    I need distinct in group concat,wmsys.wm_concat is not working in PL/SQL but its working out side PL/SQL.Am i not using function correct way ? my Oracle version 11g,R2.
    Not Working in PL/SQL :
    create or replace procedure ttp
    as
    begin
    insert into tt1(cnt1,deptno1,sumt,cbranch)
    select count(no),count(deptno),sum(tot),wmsys.wm_concat(DISTINCT branch) from tt group by deptno;
    commit;
    end;
    ERROR :
    LINE/COL ERROR
    4/1 PL/SQL: SQL Statement ignored
    5/48 PL/SQL: ORA-30482: DISTINCT option not allowed for this function
    16:42:43 SQL>
    Working in SQL :
    select count(no),count(deptno),sum(tot),wmsys.wm_concat(distinct branch) from tt group by deptno;
    Thanks,
    Edited by: user607128 on Oct 30, 2011 1:50 PM

    Hi,
    I don't know why DISTINCT doesn't work in PL/SQL. You might need to do two GROUP BYs; one to get distinct branches, and the other to collapse that down to one row per deptno:
    INSERT INTO tt1 (cnt1, deptno1, sumt, cbranch)
    WITH   got_distinct_branch     AS
         SELECT    deptno
         ,       branch
         ,       COUNT (no)          AS count_no
         ,       COUNT (deptno)     AS count_deptno
         ,       SUM (tot)          AS sum_tot
         FROM       tt
         GROUP BY  deptno
         ,            branch
    SELECT       SUM (count_no)
    ,       SUM (count_deptno)
    ,       SUM (sum_tot)
    ,       LISTAGG (branch, ',') WITHIN GROUP (ORDER BY branch)
    FROM       got_distinct_branch
    GROUP BY  deptno
    ;You didn't post CREATE TABLE and INSERT statements for your tables, so I can't test it.
    Don't use wm_concat; it's not documented. Since you have Oracle 11.2, you can use LISTAGG, or, if you really need the DISTINCT feature outside of PL/SQL, the user-defined STRAGG which you can copy from the following page:
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402

  • 2010 Forum Quotes

    In remembrance of last year let me share my collected (funny) quotes from this forum:
    | 2010 PL/SQL Forum |
    Aketi> This thread is to discussion what is difference between wmsys.wm_concat and ListAgg.
    michaels2> You might then also introduce a comparison with 11g's similar (undocumented) stragg function:
    BluShadow>Have they been letting Tom at the source code again!
    Slow_Moe>There is most certainly a difference here. I use Toad 10.5.1.3 in both cases, just pressing the button.
    We do have some issues with the database, performance wise, though. I'm starting to think it is
    not completely sane (upgraded from 9i, not installed from scratch).
    BluShadow>That could be an issue in Toad.
    We've just installed Toad 10.5.1.3 and they certainly have seemed to manage to introduce a multitude of bugs in it.
    Op presenting some large select> This was actually a query that someone else put together and asked me to fix - so I'm not actually sure what their requirements are.
    Tubby> I think you should stop immediately what you are doing, i mean this seriously.
    If you don't understand the requirement there's very little chance you'll have any measurable success tuning this. The bulk of tuning (in my experience anyways) comes from understanding the data, their distributions and the exact requirement needed by the query in question. Sure you can throw in the odd bit of technical magic to save the day, but i would say this is the exception and not the norm.
    It's entirely possible you could transform this query into an elegant 20 line query that executes in a fraction of the time, however, that's never going to happen without understanding the question you are trying to answer.
    oP> Thanks for Information.I will do in the below method.Confirm me it is OK or not
    amarkiewicz >I'm not exactly a machine and can't parse it as well as the db can. It looks like a good start. Try it out and see what happens.
    sybrand_b>BTW will anything bad happen if you post a question consisting of more than 1 line. Salary substracted? Fingers chopped off by your boss?
    John Spencer (about naming conventions in Sql Server Db)>
    Given that an unqualified name is usually resolved (only?) in the current database, and doing master.dbo.sp_help table_name gets tedious after a while, they chose to use the sp_ convention to "force" initial resolution to the master database.
    Billy> So it was introduced just because they were lazy to type a fully qualified name and rather hacked the object resolution scope and introduce exceptions to what should be sacred grounds - consistent behaviour in scope resolution....
    Makes sense... if you happen to be a Ferengi and dislike everything Vulcan...
    OP>I am finding out that explain plan and running the optimzer tools in SQL Navigator is much to read than in sql plus.
    SomeoneElse>I shall alert the media.
    OP>My database session has been locked. Please suggest something.
    Karthick_Arp> Kill the session.
    Saubhik>Find the lock and kill....
    sree>pls try alter system kill session 'SID,SERIAL#
    Ulfet>Firstly investigate why session was locked. If necessary kill session.
    Sven>All of you are session terrorists! All you want to do is kill...kill...kill! ;)
    William>The killing is regrettable but necessary to liberate the session ;)
    Billy>With most the advice offered here, you just as well can get some PE4/C4 (plastic explosives) and blow up the server. That will not only kill the "locked" session, but also kill any other potential and imagined problem arising from that server.
    As William said - a session is never locked. There is no such concept at session level in Oracle. A session can be blocked - something very different from being locked.
    A session can also become unresponsive for a number of other reasons. Stuck in an infinite loop courtesy of buggy code. Doing tons of I/O courtesy of bad SQL design that results in a cartesian join. Or slow because of just plain shoddy PL/SQL code. Etc.
    Killing that session will not tell you anything about what happened, what went wrong, and how to prevent that from happening again.
    The very first step when dealing with any IT problem is to identify the problem. Once you know WHAT the problem is, you will know HOW to address it. Killing the problem.. that only works as a solution in the military. Not in software engineering.
    Toon Koppelaars>Don't believe everything you read on the internet (even not this...)
    OP> what is the view?
    JS1>It's what you see when you look out your window.
    Someoneelse>http://theview.abc.go.com/
    OP> the application generates dynamically the condition in the form :
    where <condition_string> in ( 'red','blue')
    Billy> You need to consider what that means in actual terms.. in terms of the data model, in terms of dealing with end user requirements, and it terms of database performance.
    In most cases. this approach is fatally flawed. Is due to a poor data model and not correctly dealing with end user requirements in a performant and scalable fashion. Never mind trashing fundamental database concepts dealing with performance and sharable SQL.
    OP>of course, thats what I know. I looked for a quick workaround.
    Billy> So instead of running into a brick wall at a 90 degree angle, you want to see if it hurts less using a 60 degree angle?
    I would have thought that not running into the brick wall at all was the aim...
    BluShadow(after some heated discussion about pros and cons of SQL language syntax elements)>
    SQL> select * from dual;
    SQL> please process your datafiles and return the data from all of the columns from the table that is referenced by the name of dual;I know which I'd prefer....
    Munky>I like the way you said 'please'. Maybe, rather than all this 'tuning' nonense - response time could be directly correlated to how polite you are!
    Boneist>That's certainly true of the forums, if not the database! *{;-)
    Karthick_Arp>I would wish for MAKE_ME_RUN_FAST hint
    Munky>But surely this would be better?
    SQL> set timing on
    SQL> Hi ther Mr. DB (I do hope you don''t mind me calling you that?).
         I''ve got some super stuff for you to do and I would be just
         thrilled if you could do it expediently.
         However  - no pressure - you just do it at your earliest convenience.
         What I''m look for is all of the data from all of the columns
         that you've got in that dual fellow.
         Would that be okay?
         Jolly good, and thanks again old boy! xxx;
    D
    X
    Elapsed: 00:00:00.01
    SQL>----------
    Hari>Sorry Blushadow if my information went wrong, I copied it from a OTN Forum
    Blueshadow>Don't believe everything you read on the OTN forums, it's full of people posting inaccurate information. ;)
    William (in the "Wishlist" thread">I'd like BETWEEN to have an optional EXCLUSIVE clause for each end of the range so we didn't have to keep rewriting it using AND x < y etc.
    I'd like them to drop the stupid MODEL clause so I didn't have to feel inadequate for not understanding it, along with GROUP BY CUBE and while they're at it, XML.----------
    OP>If I need to remove some sensitive data from single field of a row in database (10g and 11g), is there a function provided by Oracle Db to do that? Just simplely set the value to null is not enough. I heard that 3 passes or more with certain set of values can do the trick. But I am not quite sure about it. Any suggestions? Thanks.
    hoek>Tricks don't exist in Oracle database-world. Please turn you mumbo-jumbo into somethng humans and databases can read and understand.
    Munky>You could get Prime's armed DBA to hack away at it? When NULL is not enough, use a chainsaw (sure I heard that somewhere?).
    John>Wouldn't it be a bit insensitive to shoot sensitive data ? (armed DBA ... could be a new role ;) )
    Munky>{code}SQL> CONNECT SYS as ARMED_DBA{code}
    http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1156151916789#25335122556076
    user11268895>..but i was wondering why:
    user11268895> select count(distinct rowid) from mytable
    user11268895> select count(rowid) from mytable
    user11268895>were not rewirtten to the same thing (syntaxically/logically they are not the same, but an optimization can be made there (removal of the aggregate))...
    BluShadow>It's probably not automatically rewritten to teach you a lesson for not understanding what rowid is and not knowing that rowid's are already distinct. :P
    3360>Also it is a game of catch up. When Oracle protects developers from doing one stupid thing they seem to be infinitely resourceful in coming up with new ways to shoot themselves in the foot.
    http://www.quotedb.com/quotes/2701
    op> what is scalar subfactory .what is the purpose of it.
    MichaelS>Do you - by any chance - actually mean Scalar Subquery?
    op> scalar subfactory usage in performance tuning
    WHiteHat>do you mean a sub-contracted industrial plant specialising in extreme musical instrument manipulation?
    OP>I am getting an ORA-03113: error when executing the below trigger
    CharlesRoos>This happens when you come to work in the morning run first query without reconnecting to database firstly.
    OP: find first three highest salary from emp for each dept
    Sven: John, Paul and George.
    Munky: Got em! They were hiding under my desk! Do I get a reward for returning them safely?
    OP: query to find first three highest salary from employee table for each department
    Maxim: But really interesting is , what their salaries are... And whether their company still hire...
    Munky: "query to find first three highest salary from employee table for each department " => I've have made the appropriate enquiry. Hope this helps!
    Dbb: I suspect it is for fire them...
    Riedelme: "Sven wrote: John, Paul and George." What do you have against Ringo?????
    Munky: The OP only wants to fire the three that earned the most (obviously forgetting any additional income made from doing voice overs for children's programs)
    Sven: Afaik Ringo doesn't earn as much as the other three.
    OP: asking some question about dependencies
    OP (30 minutes later): Is any one there????
    Someoneelse: "Just nod if you can hear me"
    OP: I'm noding can u c me?
    Jay> First of all, whenever i try and put my attempted code for this in a thread it says 'sorry content not allowed'.
    BluShadow> It could be that your code contains some words that aren't permitted on the forums. If it contains certain words that spammers use a lot e.g. "S h o e s" then it may be rejected by the forum on the belief that you're trying to post spam.
    Billy> Or "d i s c o u n t" and similar words..
    Munky> But not 'bollocks'! <cringes - sorry couldn't resist>
    BluShadow>Of course not, we're allowed to talk bollocks. We do most of the time anyway. ;)
    Mosaq> and some of it is necessory sometimes ;-)
    | APEX forum 2010 |
    Peter to Carl>but if you say it's possible, it should work!
    carl>I say all sorts of things, that doesn't mean that it "should" work just that I think it "should" work . ;)
    j4john>Now that Craig Venter is creating synthetic life and the Higgs boson is wearing a false nose to evade detection, it's probably time to up the game in Apex file uploads.

    This is the great thread ;-)
    My favorite threads are below.
    Munky posted great reply :8}
    SQL Query Help
    order in a connect by

  • Planning Form Metadata SQL Extract Query

    I am trying to find Oracle SQL logic that I can use to extract metadata that defines planning web forms from the HSP_OBJECT, HSP_FORM_...etc. tables. I need this information so that I can query and analyze metadata changes that could impact planning web forms. In particular I need to get a list of all "Account" dimension members that are within a form that are set for "Input" data property in the form. We are on Planning 11.1.2.1.101.8. Any help on this is very much appreciated.

    Oh my goodness, this saved my life, and probably the life of several other people. Thanks Jake and Brian.
    I took Brian's code (and oh yeah, Kscope is an awesome and useful conference) and modified it for Oracle.
    NB -- wm_concat is not a totally supported keyword, and (as far as I can tell) not supported before 11g. Here's a really good review of it and other strategies:
    Let us discussion at wmsys.wm_concat VS ListAgg
    Regardless, I am nothing if not a SQL hack, it works in my client's environment (really nicely, I must say), and even though this thread is old, I throw it out there so no one else has to do this.
    And with that disclaimer, the Oracle version of the query:
    SELECT
      o.OBJECT_NAME AS Form_Name
          SELECT
            wm_concat(flo.OBJECT_NAME)
          FROM
            HSP_FORM_LAYOUT fl
          INNER JOIN
            HSP_OBJECT flo on fl.DIM_ID = flo.OBJECT_ID
          WHERE
            fl.FORM_ID = f.FORM_ID AND fl.LAYOUT_TYPE = 0
        AS POV_Dimensions
          SELECT
            wm_concat(flo.OBJECT_NAME)
          FROM
            HSP_FORM_LAYOUT fl
          INNER JOIN
            HSP_OBJECT flo on fl.DIM_ID = flo.OBJECT_ID
          WHERE fl.FORM_ID = f.FORM_ID AND fl.LAYOUT_TYPE = 1
        AS Page_Dimensions
          SELECT
            wm_concat(flo.OBJECT_NAME)
          FROM
            HSP_FORM_LAYOUT fl
          INNER JOIN
            HSP_OBJECT flo on fl.DIM_ID = flo.OBJECT_ID
          WHERE
            fl.FORM_ID = f.FORM_ID AND fl.LAYOUT_TYPE = 2
        AS Row_Dimensions
          SELECT
            wm_concat(flo.OBJECT_NAME)
          FROM
            HSP_FORM_LAYOUT fl  
          INNER JOIN
            HSP_OBJECT flo on fl.DIM_ID = flo.OBJECT_ID
          WHERE
            fl.FORM_ID = f.FORM_ID AND fl.LAYOUT_TYPE = 3
        AS Column_Dimensions
          SELECT
            wm_concat(fla.OBJECT_NAME)
          FROM
            HSP_FORM_ATTRIBUTES fa
          INNER JOIN
              HSP_OBJECT fla on fa.DIM_ID = fla.OBJECT_ID
          WHERE
              fa.FORM_ID = f.FORM_ID   
        AS Attribute_Dimensions
          SELECT
            wm_concat(fc.CALC_NAME || CASE fc.RUN_ON_LOAD WHEN 1 THEN ' (Run on load)' ELSE '' END || CASE fc.RUN_ON_SAVE WHEN 1 THEN ' (Run on save)' ELSE '' END)
          AS CALCs
          FROM
            HSP_FORM_CALCS fc
          WHERE
            fc.FORM_ID = f.FORM_ID
        AS Calcs
          SELECT
            wm_concat(aco.OBJECT_NAME)
          FROM
            HSP_ACCESS_CONTROL ac
          INNER JOIN
            HSP_OBJECT aco ON aco.OBJECT_ID = ac.USER_ID
          WHERE
            ac.OBJECT_ID = f.FORM_ID AND ac.ACCESS_MODE = 3
        AS Users_Write
          SELECT
            wm_concat(aco.OBJECT_NAME)
          FROM
            HSP_ACCESS_CONTROL ac
          INNER JOIN
            HSP_OBJECT aco ON aco.OBJECT_ID = ac.USER_ID
          WHERE
            ac.OBJECT_ID = f.FORM_ID AND ac.ACCESS_MODE = 1
        AS Users_Read
          SELECT
            wm_concat(aco.OBJECT_NAME)
          FROM
            HSP_ACCESS_CONTROL ac
          INNER JOIN
            HSP_OBJECT aco ON aco.OBJECT_ID = ac.USER_ID
          WHERE
            ac.OBJECT_ID = f.FORM_ID AND ac.ACCESS_MODE = -1
        AS Users_Denied
      , o.MODIFIED AS Last_Modified
      , o.MODIFIED_BY AS Modified_By   
    FROM
      HSP_FORM f
    INNER JOIN
      HSP_OBJECT o ON f.FORM_ID = o.OBJECT_IDRegards,
    Cameron Lackpour

  • Wm_concat(column_name) order by [SOLVED]

    The question is based on a other thread:
    column values separated by ,
    Aketi Jyuuzou Posted: Nov 23, 2007 3:17 AM
    with the next statement there will be 4 records displayed
    (there are 4 columns for this constraint)
    select constraint_name, wm_concat(column_name) over(order by position) as column_names
    from user_cons_columns
    where constraint_name='EUL5_DOC_UK_2'
    1 EUL5_DOC_UK_2     DOC_EU_ID
    2 EUL5_DOC_UK_2     DOC_EU_ID,DOC_NAME
    3 EUL5_DOC_UK_2     DOC_EU_ID,DOC_NAME,DOC_BATCH
    4 EUL5_DOC_UK_2     DOC_EU_ID,DOC_NAME,DOC_BATCH,DOC_FOLDER_ID
    is it possible to select only the last (4) record?
    Thanks in advance..

    Note that wmsys.wm_concat is undocumented and unsupported.
    It looks like the script below, which I use to show me the constraints on a table, might be useful to you:
    column "Constraint" format a20
    column "Kolom(men)" format a40
    column "Soort" format a11
    column "Verwijst naar" format a23
    column "Inhoud check constraint" format a36 truncate
    accept P_TABEL char prompt 'Van welke tabel wil je de constraints zien? '
    set verify off
    select c.constraint_name "Constraint"
         , case c.constraint_type
           when 'P' then 'Primary key'
           when 'U' then 'Unique key'
           when 'R' then 'Foreign key'
           when 'C' then 'Check'
           else 'Anders: ' || c.constraint_type
           end "Soort"
         , rtrim(cc.cols,',') "Kolom(men)"
         , case when c.r_owner is not null then c.r_owner || '.' || c.r_constraint_name end "Verwijst naar"
         , c.search_condition "Inhoud check constraint"
      from user_constraints c
         , ( select constraint_name
                  , p
                  , c cols
               from user_cons_columns
              where table_name = upper('&&P_TABEL')
              model
                    partition by (constraint_name)
                    dimension by (nvl(position,row_number() over (partition by constraint_name order by null)) p)
                    measures (column_name c)
                    ( c[any] order by p desc = c[cv()] || ',' || c[cv()+1]
           ) cc
    where c.constraint_name = cc.constraint_name
       and cc.p = 1
    order by
           case c.constraint_type
           when 'P' then 1
           when 'U' then 2
           when 'R' then 3
           when 'C' then 4
           else 5
           end
         , c.constraint_name
    undefine P_TABEL
    set verify onGroet,
    Rob.

  • How to get rows values in a column only ?

    How to get all returned values in rows in a column.
    e.g., a query gives output as :
    123
    234
    233
    12121
    all in different rows. But i want the result like this:
    123,234,233,12121.All in a single row and a single column .
    How is this possible ?

    prakash wrote:
    hi ,
    Use the following example
    CREATE or  replace  FUNCTION fn_return_row
    RETURN VARCHAR2
    IS
    v_row   VARCHAR2 (32767);
    BEGIN
    FOR curr_row IN (SELECT ename
    FROM emp11)
    LOOP
    v_row := v_row ||','|| curr_row.ename;
    END LOOP;
    RETURN v_row;
    EXCEPTION
    WHEN OTHERS
    THEN
    RETURN NULL;
    END fn_return_row;
    select fn_return_row from dual ;Thanks,
    P PrakashThere's no need to use PL/SQL when SQL provides adequate functionality to do it.
    The title of the thread is misleading as turning rows into columns is called pivoting, but the description of the issue wanting to join all the rows together into a single column, is actually called string aggregation.
    As already demonstrated it can be done several ways.
    1. with XML functionality
    2. using the SYS_CONNECT_BY_PATH method
    and if you have 11gR2, there's...
    3. the new LISTAGG analytical function.
    There is also an undocumented WMSYS.WM_CONCAT function, though this isn't as flexible as other methods in that you can't control the order of the aggregated data so easily, and using such undocumented functions in production code is dangerous, as the functionality could change in future versions of Oracle, as well as it's use making your code such that Oracle will not provide support if the code with issue is using it.

  • How could I copy contraints from one database to another?

    Hi,
    I have a specific problem.
    I have taken a datadump and executed in another database. Some how the contraints were not copied.
    So I created following script to genrated alter statement and then run the script in target database:
    declare
    cursor get_cons is
    select distinct dc.table_name table_name, decode ( substr(dc.constraint_name,1,3), 'SYS', ' ', 'CONSTRAINT ' dc.constraint_name ) contraint, wmsys.wm_concat(ucc.column_name) over ( partition by dc.constraint_name order by dc.constraint_name ) cols
    from user_constraints dc,
    user_cons_columns ucc
    where dc.table_name like '%'
    and dc.constraint_type = 'P'
    and dc.table_name = ucc.table_name
    and dc.constraint_name = ucc.constraint_name;
    lv_sql varchar2(2000);
    begin
    for i in get_cons
    loop
    lv_sql := 'ALTER TABLE '
    I.TABLE_NAME
    +' ADD ('+
    i.contraint
    +' PRIMARY KEY ( '+
    I.COLS
    +' )); ';+
    dbms_output.put_line( lv_sql );
    end loop;
    end;
    Is there a better way to do it?
    Thank You,
    Ranjeeth

    Hi,
    do u have idea about move data from development environment to production environment.
    what is the simpleast way. suppose if we refer DATAPUMP or EXP/IMP. How to do it.
    through EXP command i am exporting full database or specified tables. but problem is i am not able import which i exported tables.
    can u give me the steps to how to import .DMP files through command prompt.
    Thanks
    Venkat.

  • How to Concatenate Multiple Column Records from multiple tables

    my question is
    there are three tables like A,B,C
    i want the data from these tables with the help of relation
    select a.simno,b.item_code,c.desc
    from A a,B b,C c
    WHERE a.ms=b.ms and
    b.item_code=c.item_code
    and a.ms=c.ms
    the output for this query which i am getting is
    simno item_code desc
    1 i1 abc
    1 i2 def
    1 i3 xyz
    2 i4 gtr
    2 i5 poi
    but i want the output in this
    simno details
    1 abc#def#xyz
    2 gtr#poi
    and so on
    if it dispayes the output inthis manner i can save as ".csv" file

    Hi,
    There are different Solutions you can achieve
    Refer to Asktom : http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:2196162600402
    SQL> create table test(simno number, itemcode varchar2(5), desc1 char(5))
    Table created.
    SQL> insert into test(simno,itemcode,desc1) values (1 ,'i1' ,'abc');
    1 row created.
    SQL> insert into test(simno,itemcode,desc1) values (1 ,'i2' ,'def') ;
    1 row created.
    SQL> insert into test(simno,itemcode,desc1) values (1 ,'i3' ,'xyz') ;
    1 row created.
    SQL> insert into test(simno,itemcode,desc1) values (2 ,'i4' ,'gtr');
    1 row created.
    SQL> insert into test(simno,itemcode,desc1) values (2 ,'i5' ,'poi');
    1 row created.
    SQL> select simno,wmsys.wm_concat(desc1) CONCAT
      2  from test
      3  group by simno;
         SIMNO
    CONCAT
             1
    abc  ,def  ,xyz
             2
    gtr  ,poi- Pavan Kumar N

  • Query is Slower in PL/SQL than in SQL*Plus ?

    I have a query that executes quiet fast in SQL*Plus (<1 second) but with EXECUTE IMMEDIATE withing an PL/SQL block its performance is really poor (=20 times slower)
    I am using the agregation function WMSYS.WM_CONCAT and I figured out that the poor PL/SQL performance must be related somehow to this function...
    I don't get why in SQL*Plus the query executes that much faster... Any ideas/solutions?
    Thanks!
    My PL/SQL query:
    EXECUTE IMMEDIATE 'INSERT INTO ' || temp_table_opt || '
    SELECT DISTINCT a.hs as HS, a.ht as HT, a.vehicle_id as VEHICLE_ID, c.option_id as OPTION_ID, WMSYS.WM_CONCAT(e.av_checked) as AV,
    d.vehicle_id || '';'' || d.option_code || '';'' || d.option_type || '';'' || d.manuf_name as COMPOUND_KEY
    FROM jumla.ax_vid a, jumla.version b, jumla.equipment c, jumla.option_list d, jaxlink_data.checked e
    WHERE a.hs = SUBSTR(''' || phsht || ''', 1, 2)
    AND a.ht = SUBSTR(''' || phsht || ''', -2, 2)
    AND b.vehicle_id = a.vehicle_id
    AND c.vehicle_id = a.vehicle_id
    AND d.vehicle_id = a.vehicle_id
    AND b.id_106 IN (''2'', ''4'', ''X'')
    AND d.option_type <> ''P''
    AND d.option_id = c.option_id
    AND e.hs = a.hs
    AND e.ht = a.ht
    AND e.schema_id = c.schema_id
    AND e.option_code = d.option_code
    AND e.description = d.manuf_name
    GROUP BY a.hs, a.ht, a.vehicle_id, c.option_id, d.vehicle_id || '';'' || d.option_code || '';'' || d.option_type || '';'' || d.manuf_name';

    > I am using the agregation function WMSYS.WM_CONCAT and I figured
    out that the poor PL/SQL performance must be related somehow to this
    function...
    Wrong.
    Who executes the SQL that is created?
    Answer - does not matter where the SQL comes from, from a PL procedure, Java program, SQL*Plus, TOAD or whatever, the SQL is parsed by the SQL engine, execution plan created by the CBO and stored in the SQL Shared Pool.
    An EXECUTE IMMEDIATE is a PL command that sends the string to the SQL engine to be processed. Just as SQL*Plus sends a string to the SQL engine to be processed.
    So how can the very same SQL be faster from SQL*Plus and slower from somewhere else?
    Nothing to do with where it comes from, but everything to do wrt the session that the SQL is being executed in. Issues such as settings for that session (which can be differ from session to session). Scope. Context. Etc.

  • Column values separated by ,

    Suppose say I have table TAB1 with the following data :
    COL1 COL2
    1 A
    1 B
    1 C
    2 M
    2 N
    2 O
    2 P
    2 Q
    3 S
    3 T
    How would I retrieve the data in the following format ?
    1 A,B,C
    2 M,N,O,P,Q
    3 S,T

    Hi Laurent Schneider.
    That a good solution.
    I researched that.
    SQL> select version from v$instance;
    VERSION
    10.2.0.1.0
    SQL> create table IDTable(ID,Val) as
      2  select 10,'abc' from dual union all
      3  select 10,'abc' from dual union all
      4  select 10,'def' from dual union all
      5  select 10,'def' from dual union all
      6  select 20,'ghi' from dual union all
      7  select 20,'jkl' from dual union all
      8  select 20,'mno' from dual union all
      9  select 20,'mno' from dual;
    SQL> col enames for a40
    SQL> select ID,wmsys.wm_concat(Val) as enames
      2    from IDTable
      3  group by ID
      4  order by ID;
    ID  ENAMES
    10  abc,abc,def,def
    20  ghi,jkl,mno,mno
    SQL> select ID,wmsys.wm_concat(distinct Val) as enames
      2    from IDTable
      3  group by ID
      4  order by ID;
    ID  ENAMES
    10  abc,def
    20  ghi,jkl,mno
    SQL> select ID,wmsys.wm_concat(Val order by Val) as enames
      2    from IDTable
      3  group by ID
      4  order by ID;
    select ID,wmsys.wm_concat(Val order by Val) as enames
    ORA-00907:
    SQL> select ID,Val,wmsys.wm_concat(Val) over(partition by ID) as enames
      2    from IDTable
      3  order by ID;
    ID  VAL  ENAMES
    10  abc  abc,abc,def,def
    10  abc  abc,abc,def,def
    10  def  abc,abc,def,def
    10  def  abc,abc,def,def
    20  ghi  ghi,jkl,mno,mno
    20  jkl  ghi,jkl,mno,mno
    20  mno  ghi,jkl,mno,mno
    20  mno  ghi,jkl,mno,mno
    SQL> select ID,Val,wmsys.wm_concat(Val) over(order by ID,Val) as enames
      2    from IDTable
      3  order by ID;
    ID  VAL  ENAMES
    10  abc  abc,abc
    10  abc  abc,abc
    10  def  abc,abc,def,def
    10  def  abc,abc,def,def
    20  ghi  abc,abc,def,def,ghi
    20  jkl  abc,abc,def,def,ghi,jkl
    20  mno  abc,abc,def,def,ghi,jkl,mno,mno
    20  mno  abc,abc,def,def,ghi,jkl,mno,mno

  • Query to display concatenated values from various records based on the keyn

    Dear all
    I have a table which has info like this
    keyno valueno
    20 1200
    21 1345
    20 1095
    20 9094
    21 3433
    22 5031
    21 199
    20 232
    the output has to be like this
    20 1200/1095/9094/232
    21 1345/3433/199
    22 5031
    is there any way to do this or do i have to get this done using an anonymous block
    i have intended to display this output as an LOV in oracle forms
    Kindly help me in this regard , iam just stuck
    With Warm Regards
    ssr

    Dear guys -- Jeneesh and Rob
    Thanks for the replies ,
    Jeneesh , I couldnt get this STRAGG ... i dont think it is a function provided by Oracle. So i couldnt make use of this
    and thanks Rob The SYS_CONNECT_BY_PATH seemed too confusing for my little brain rather i found out something simple
    wmsys.wm_concat which solved my reqmt ...
    I am yet to explore it and defenitly i have to work with this SYS_CONNECT_BY_PATH and then try with my reqmt ... as for now its solved

  • Conerting multiple rows into sinlge row

    Hi All,
    Suppose the table is like given below,
    EmpId     Technology
    1     Java
    1     Oracle
    1     .Net
    1     MySQL
    Here the above table (Technology) says the list of technologies working by Employee 1.
    Now I want a query, which can give result like below,
    EmpId     Tech_java     Tech_oracle     Tech_.net     Tech_mysql
    1     java     Oracle     .Net     MySQL
    The data base is oracle 10g
    Please let me know if any issue.
    Thanks

    34MCA2K2 wrote:
    Just another way of doing it :-)
    with t as (
    select 1 empid, 'Java' technology from dual union
    select 1, 'Oracle' from dual union
    select 1, '.Net' from dual union
    select 1, 'MySQL' from dual union
    select 2 , 'PHP' from dual union
    select 2, 'Informatica' from dual union
    select 2, 'COGNOS' from dual union
    select 2, 'MSSQL' from dual
    SELECT wm_concat(technology), empid FROM t group by empid
    What? Using an undocumented function that can change in the future without notice, and one that is not recommended by Oracle, or by Tom Kyte (Re: DISTINCT not working with  wmsys.wm_concat or any other experts?
    Please do not recommend undocumentated functionality, as you could be responsible for breaking someone's commercial application.

  • Query way slower as APEX report than in SQL client

    Hi,
    I know that this topic has been discussed many times. Usually the problem is that the query returns at least thousands of data. Unfortunately, not in my case. The query returns the top 10 applications for the current month only, ordered descending by the number of transactions:
    select APP_KEY, REQUEST_COUNT
    from
        (select APP_KEY, sum(REQUEST_COUNT) as REQUEST_COUNT,
            row_number() over(order by sum(REQUEST_COUNT) desc, APP_KEY) RN
        from YEAR_REQUEST_COUNT
        where (RESPONSE_CODE between 200 and 299 or RESPONSE_CODE < 100) and
            REQUEST_TIME >= trunc(sysdate, 'mm') and
            REQUEST_TIME < trunc(sysdate)
        group by APP_KEY)
    where RN <= 10
    order by RN
    In TOAD it takes approx. 1 minute, in APEX its SQL command tool approx. 80 seconds and as a simple classic report approx. 6 minutes!
    That's the query plan I get with TOAD and APEX:
    | Id  | Operation                     | Name               | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT              |                    |  7028 |  1976K|       |   300K  (3)| 01:30:13 |       |       |
    |   1 |  SORT ORDER BY                |                    |  7028 |  1976K|  2112K|   300K  (3)| 01:30:13 |       |       |
    |*  2 |   VIEW                        |                    |  7028 |  1976K|       |   300K  (3)| 01:30:10 |       |       |
    |*  3 |    WINDOW SORT PUSHED RANK    |                    |  7028 |   267K|       |   300K  (3)| 01:30:10 |       |       |
    |   4 |     HASH GROUP BY             |                    |  7028 |   267K|       |   300K  (3)| 01:30:10 |       |       |
    |*  5 |      FILTER                   |                    |       |       |       |            |          |       |       |
    |   6 |       PARTITION RANGE ITERATOR|                    |  8703K|   323M|       |   299K  (3)| 01:29:57 |   KEY |   KEY |
    |*  7 |        TABLE ACCESS FULL      | YEAR_REQUEST_COUNT |  8703K|   323M|       |   299K  (3)| 01:29:57 |   KEY |   KEY |
    Predicate Information (identified by operation id):
       2 - filter("RN"<=10)
       3 - filter(ROW_NUMBER() OVER ( ORDER BY SUM("REQUEST_COUNT") DESC ,"APP_KEY")<=10)
       5 - filter(TRUNC(SYSDATE@!,'fmmm')<TRUNC(SYSDATE@!))
       7 - filter("REQUEST_TIME">=TRUNC(SYSDATE@!,'fmmm') AND ("RESPONSE_CODE">=200 AND "RESPONSE_CODE"<=299 OR
                  "RESPONSE_CODE"<100) AND "REQUEST_TIME"<TRUNC(SYSDATE@!))
    I've also tried to rewrite the query, but no positive effects:
    select *
    from (
        select APP_KEY, sum(REQUEST_COUNT) as REQUEST_COUNT
        from YEAR_REQUEST_COUNT
        where (RESPONSE_CODE between 200 and 299 or RESPONSE_CODE < 100) and
            REQUEST_TIME >= trunc(sysdate, 'mm') and
            REQUEST_TIME < trunc(sysdate)
        group by APP_KEY
        order by REQUEST_COUNT desc
    where rownum <= 10
    The APEX debugger shows me that 99% of the time are spent on the step "rows loop: 15 row(s)".
    Any ideas what's going on with this query?
    Carsten

    > I am using the agregation function WMSYS.WM_CONCAT and I figured
    out that the poor PL/SQL performance must be related somehow to this
    function...
    Wrong.
    Who executes the SQL that is created?
    Answer - does not matter where the SQL comes from, from a PL procedure, Java program, SQL*Plus, TOAD or whatever, the SQL is parsed by the SQL engine, execution plan created by the CBO and stored in the SQL Shared Pool.
    An EXECUTE IMMEDIATE is a PL command that sends the string to the SQL engine to be processed. Just as SQL*Plus sends a string to the SQL engine to be processed.
    So how can the very same SQL be faster from SQL*Plus and slower from somewhere else?
    Nothing to do with where it comes from, but everything to do wrt the session that the SQL is being executed in. Issues such as settings for that session (which can be differ from session to session). Scope. Context. Etc.

  • Problem with my aggregate function

    Hello there,
    I tried to build my own string aggregate function but I've a troubles when I'm using it into my query. When I'm using it, it writes ORA904, whereas this idenfifier exists. Do you know what's wrong ?
    here my aggregate function :
    create or replace FUNCTION aggme (query_in in VARCHAR2) RETURN VARCHAR2 IS
        incoming    varchar2(4000);
        hold_result varchar2(4000);
        c sys_refcursor;
    Begin
        open c for query_in;
        loop
            fetch c into incoming;
            exit when c%notfound;
            hold_result := hold_result||','||incoming;
        end loop;
        return ltrim(hold_result,',');
    END;and here my query by using my aggregate function aggme:
    select
      RES.LASTNAME as "LASTNAME",
      RES.FIRSTNAME as "FIRSTNAME",
      aggme('select NAME from PATHOLOGY where ID= RES.PATHOLOGY_ID') as "PATHOLOGY"
    from
      TBK_RESOURCE RES

    Mustafa KALAYCI wrote:
    I think you wanted to do this:
    select
    RES.LASTNAME as "LASTNAME",
    RES.FIRSTNAME as "FIRSTNAME",
    aggme('select NAME from PATHOLOGY where ID=' || RES.PATHOLOGY_ID) as "PATHOLOGY"
    from
    TBK_RESOURCE RESby the way this is a very very bad idea doing like that. you should look for WM_CONCAT (for db version 11.1 or lower)No. Nobody should use WM_CONCAT. It's an undocumented function that is not supported by Oracle and may be changed in future versions without notice.
    All Oracle experts say not to use it, including Tom Kyte... Re: DISTINCT not working with  wmsys.wm_concat
    Below 11gR2, you should use SYS_CONNECT_BY_PATH, or a user defined function, including user defined aggregate functions such as the following example, which aggregates strings into a clob as a result...
    create or replace type clobagg_type as object
      text clob,
      static function ODCIAggregateInitialize(sctx in out clobagg_type) return number,
      member function ODCIAggregateIterate(self in out clobagg_type, value in clob) return number,
      member function ODCIAggregateTerminate(self in clobagg_type, returnvalue out clob, flags in number) return number,
      member function ODCIAggregateMerge(self in out clobagg_type, ctx2 in clobagg_type) return number
    create or replace type body clobagg_type is
      static function ODCIAggregateInitialize(sctx in out clobagg_type) return number is
      begin
        sctx := clobagg_type(null) ;
        return ODCIConst.Success ;
      end;
      member function ODCIAggregateIterate(self in out clobagg_type, value in clob) return number is
      begin
        self.text := self.text || value ;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateTerminate(self in clobagg_type, returnvalue out clob, flags in number) return number is
      begin
        returnValue := self.text;
        return ODCIConst.Success;
      end;
      member function ODCIAggregateMerge(self in out clobagg_type, ctx2 in clobagg_type) return number is
      begin
        self.text := self.text || ctx2.text;
        return ODCIConst.Success;
      end;
    end;
    create or replace function clobagg(input clob) return clob
      deterministic
      parallel_enable
      aggregate using clobagg_type;
    SQL> select trim(',' from clobagg(ename||',')) as enames from emp;
    ENAMES
    SMITH,ALLEN,WARD,JONES,MARTIN,BLAKE,CLARK,SCOTT,KING,TURNER,ADAMS,JAMES,FORD,MILLER
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2    (select 'PFL' c1, 0 c2,110 c3 from dual union all
      3     select 'LHL', 0 ,111 from dual union all
      4     select 'PHL', 1, 111 from dual union all
      5     select 'CHL', 2, 111 from dual union all
      6     select 'DHL', 0, 112 from dual union all
      7     select 'VHL', 1, 112 from dual union all
      8     select 'CPHL', 0, 114 from dual union all
      9     select 'WDCL', 1, 114 from dual union all
    10     select 'AHL' ,2 ,114 from dual union all
    11     select 'NFDL', 3, 114 from dual)
    12  --
    13  -- end of test data
    14  --
    15  select trim(clobagg(c1||' ')) as c1, c3
    16  from (select * from t order by c3, c2)
    17  group by c3
    18* order by c3
    SQL> /
    C1                                     C3
    PFL                                   110
    LHL CHL PHL                           111
    DHL VHL                               112
    CPHL AHL NFDL WDCL                    114

  • Printing data in horizontal

    Hi,
    i have the numbers i table.the table is having only one field and i want to get the output to be displayed in horizontal way..how can i get it.
    1,2,3,4,5,6,7,8,10
    the data should be displayed in this manner through query..

    hi
    just simple use wmsys.wm_concat function with column name as parameter like this :
    select wmsys.wm_concat(c5) from  a2

Maybe you are looking for

  • I need to print text on a greeting card on an HPC5500 series printer

    Hi. I have been trying to print text on a thank-you card on my HP5580 but it won't print; it gives me a "paper mismatch" error. How do I correct this? Thanks.

  • Is it ok with add 60 warehouses in B1?

    Dear All, Our compary have no factory, all production will outsourcing. We purchase the meterial and send to the outsourcing partner to make semi-production and production. We have 60 outsourcing partner. We need to know the material stock in every o

  • Going from snow leopard 10.6.8 to mtn lion

    How is the transition going from os 10.6.8 to Mountain Lion.  My system runs awesome and I am so hesitant to upgrade for some software I need. 

  • Driver prog for tcode vf01 r  script mr_print

    hi friends, i have checked out driver prog in tnapr for vf01 / mr_print but it z giving a sub routine pool prog RM08NAST. i havwe migrated dat mr_print script to smart form but it z giving errors at the declartions level. so i need to find out how th

  • Firefox won't start and XP won't let me end the process(es).

    After having used firefox for ages with no problems, I tried to open a new Firefox window, and it wouldn't open. I opened the XP task manager and tried to end all of the firefox tasks (there were at least two)... Neither of them would end. No "are yo