Column count of dynamic query

how can ı find column count of dynamic query
is there a simple way
thanks

You can use DBMS_SQL to facilitate this:
CREATE OR REPLACE FUNCTION count_sql( p_sql IN CLOB )
RETURN INTEGER
AS
        lv_cursor_id    INTEGER;
        lv_columns      DBMS_SQL.DESC_TAB;
        lv_column_count INTEGER;
BEGIN
        -- Open Cursor
        lv_cursor_id := DBMS_SQL.OPEN_CURSOR;
        -- Parse Cursor
        DBMS_SQL.PARSE
        ( c             => lv_cursor_id
        , statement     => p_sql
        , language_flag => DBMS_SQL.NATIVE
        -- Describe Columns
        DBMS_SQL.DESCRIBE_COLUMNS
        ( c       => lv_cursor_id   
        , col_cnt => lv_column_count
        , desc_t  => lv_columns
        -- Close Cursor
        DBMS_SQL.CLOSE_CURSOR(lv_cursor_id);
        RETURN lv_column_count;
END count_sql;
/Example:
SQL > SELECT * FROM V$VERSION;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
PL/SQL Release 11.2.0.1.0 - Production
CORE    11.2.0.1.0      Production
TNS for 32-bit Windows: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
SQL > SELECT count_sql('SELECT dummy, dummy, CASE WHEN dummy = ''X'' THEN 1 ELSE 0 END AS col FROM DUAL') FROM DUAL;
COUNT_SQL('SELECTDUMMY,DUMMY,CASEWHENDUMMY=''X''THEN1ELSE0ENDASCOLFROMDUAL')
                                                                           3
SQL > SELECT count_sql('SELECT dummy, dummy, dummy, ''Y'' FROM DUAL') FROM DUAL;
COUNT_SQL('SELECTDUMMY,DUMMY,DUMMY,''Y''FROMDUAL')
                                                 4Hope this helps!

Similar Messages

  • Dynamic orderby clause for multiple columns with out Dynamic query

    Hi,
            I've a query like
    "select  * from tablename order by column1,column2,column3,column4,column5,column6"
    in the above query the order by column will be dynamically changed. The query is placed in a stored procedures and the order by column will come by parameter.
       For ex: @orderbycol = column2,column1,column3,column4,column5,column6
                                         or
                    @orderbycol = column3,column2,column1,column4,column5,coumn6
    How can we manage the order by clause as dynamically without go to dynamic query.

    ORDER BY CASE @sortcol1
                 WHEN 'col1' THEN col1
                 WHEN 'col2' THEN col2
             END,
             CASE @sortcol2
                 WHEN 'col1' THEN col1
                 WHEN 'col2' THEN col2
             END,
    Note: these CASE expressions assumes that all columns have the same data type.
    You could consider sorting in the presentation layer instead.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Finding column count with dynamic columns and dynamic tables

    I've done some PL/SQL for awhile now but was trying to devise a solution for the following problem:
    I wish to find the number of times a specific value for a column exists in all the tables that contain the field and I have access to see with the current user. The column name and value will be passed in via parameters.
    I was hoping to use something like
    select table_name from all_tab_columns where column_name = <variable table name>;
    then use the results from this to create a select statment based off the tables from the select above. I know the difference between dba_tab_columns and all_tab_columns - I want to make sure that I only retrieve the values i have access to.
    Can anyone point me to some guide / website / reference material I can read to catch up on the idea of creating this statment?
    Thank you.

    Hi,
    it's a test version.
    You can naturally tune it, but it seemed to work:
    declare
    pi_column VARCHAR2(30) := 'DEPTNO';
    pi_value VARCHAR2(4000) := '20';
    v_count NUMBER := 0;
    v_count_tab NUMBER;
    BEGIN
    FOR I IN (select owner, table_name from dba_tab_columns
              where column_name = pi_column
    LOOP
        EXECUTE IMMEDIATE 'SELECT count(*) FROM '||i.owner||'.'||i.table_name||
                          ' WHERE '||pi_column||' = :pi_value'  INTO v_count_tab USING pi_value; 
        v_count := v_count + v_count_tab;
    END LOOP;                   
    dbms_output.put_line(v_count);
    END;Regards

  • Setting Column Names in Dynamic Pivot Query

    Hi all,
    I'm having trouble setting column names in a dynamic pivot query and was wondering if someone could please help me figure out what I need to do.
    To help you help me, I've setup an example scenario in my hosted account. Here's the login info for my hosted site at [http://apex.oracle.com]
    Workspace: MYHOSTACCT
    Username : DEVUSER1
    Password : MYDEVACCTAnd, here is my test application info:
    ID     : 42804
    Name   : dynamic query test
    Page   : 1
    Table 1: PROJECT_LIST         (Alias = PL...  Listing of Projects)
    Table 2: FISCAL_YEAR          (Alias = FY...  Lookup table for Fiscal Years)
    Table 3: PROJECT_FY           (Alias = PF...  Intersection table containing project fiscal years)
    Table 4: PROJECT_FY_HEADCOUNT (Alias = PFH... Intersection table containing headcount per project and fiscal year)Please forgive the excessive normalization for this example, as I wanted to keep the table structure similar to my real application, which has much more going on.
    In my sample, I have the "Select Criteria" region, where the user specifies the project and fiscal year range that he or she would like to report. Click the Search button, and the report returns the project headcount in a pivoted fashion for the fiscal year range specified.
    I've got it working using a hard-coded query, which is displayed in the "Hardcoded Query" region. In this query, I basically return all years, and set conditions on each column which determines whether that column should be displayed or not based on the range selected by the user. While this works, it is not ideal, as there could be many more fiscal years to account for, and this is not very dynamic at all. Anytime a fiscal year is added to the FISCAL_YEAR table, I'd have to update this page.
    So, after reading all of the OTN SQL pivot forums and "Ask Tom" pivot thread, I've been able to create a second region labeled "Dynamic Query" in which I've created a dynamic query to return the same results. This is a much more savvy solution and works great; however, the column names are generic in the report.
    I had to set the query to parse at runtime since the column selection list is dynamic, which violates SQL rules. Can anyone please help me figure out how I can specify my column names in the dynamic query region to get the same column values I'm getting in the hardcoded region?
    Please let me know if you need anymore information, and many thanks in advance!
    Mark

    Hi Tony,
    Thanks so much for your response. I've had to study up on the dbms_sql package to understand your function... first time I've used it. I've fed my dynamic query to your function and see that it returns a colon delimited list of the column names; however, I think I need a little more schooling on how and where exactly to apply the function to actually set the column names in APEX.
    From my test app, here is the code for my dynamic query. I've got it in a "PL/SQL function body returning sql query" region:
    DECLARE 
      v_query      VARCHAR2(4000);
      v_as         VARCHAR2(4);
      v_range_from NUMBER;
      v_range_to   NUMBER;         
    BEGIN
      v_range_from := :P1_FY_FROM;
      v_range_to   := :P1_FY_TO;
      v_query      := 'SELECT ';
      -- build the dynamic column selections by looping through the fiscal year range.
      -- v_as is meant to specify the column name as (FY10, FY11, etc.), but it's not working.
      FOR i IN v_range_from.. v_range_to  LOOP
        v_as    := 'FY' || SUBSTR(i, 3, 4);
        v_query := v_query || 'MAX(DECODE(FY_NB,' || i || ',PFH_HEADCOUNT,0)) '
          || v_as || ',';
      END LOOP;
      -- add the rest of the query to the dynamic column selection
      v_query := rtrim(v_query,',') || ' FROM ('
        || 'SELECT FY_NB, PFH_HEADCOUNT FROM ('
        || 'SELECT FY_ID, FY_NB FROM FISCAL_YEAR) A '
        || 'LEFT OUTER JOIN ('
        || 'SELECT FY_ID, PFH_HEADCOUNT '
        || 'FROM PROJECT_FY_HEADCOUNT '
        || 'JOIN PROJECT_FY USING (PF_ID) '
        || 'WHERE PL_ID = ' || :P1_PROJECT || ') B '
        || 'ON A.FY_ID = B.FY_ID)';
      RETURN v_query;
    END;I need to invoke GET_QUERY_COLS(v_query) somewhere to get the column names, but I'm not sure where I need to call it and how to actually set the column names after getting the returned colon-delimited list.
    Can you (or anyone else) please help me get a little further? Once again, feel free to login to my host account to see it first hand.
    Thanks again!
    Mark

  • Converting rows to columns using dynamic query.

    I am trying to use the below code that I founnd on the web to conver rows to columns. the reason that I want to use dynamic query is that the number of rows are not know and changes.
    declare
        lv_sql varchar2(32767) := null ;
    begin
        lv_sql := 'SELECT Iplineno ';
        for lv_rec in (SELECT distinct vendor from bidtabs  where letting = '10021200' and call ='021')
        loop
            lv_sql :=   lv_sql
                        || CHR(10)
                        || ', MAX( DECODE( vendor, '
                        || chr(39)
                        || lv_rec.vendor
                        || CHR(39)
                        || ', bidprice, NULL ) ) as "'
                        || lv_rec.vendor
                        || '" ' ;
        end loop;
        lv_sql :=   lv_sql
                    || CHR(10)
                    || 'FROM bidtabs  where letting =  ''10021200''  and call =  ''021''  and lineflag = ''L''  '
                    || CHR(10)
                    || 'GROUP BY iplineno ;' ;
    here is the result
    BIDPRICE     CALL     IPLINENO     LETTING     VENDOR
    9,585     021     0010     10021200     C0104        
    1,000     021     0020     10021200     C0104        
    1,000     021     0030     10021200     C0104        
    17     021     0040     10021200     C0104        
    5     021     0050     10021200     C0104        
    11,420     021     0010     10021200     K0054        
    1,100     021     0020     10021200     K0054        
    1,100     021     0030     10021200     K0054        
    5     021     0040     10021200     K0054        
    3     021     0050     10021200     K0054        
    8,010     021     0010     10021200     V070         
    900     021     0020     10021200     V070         
    1,320     021     0030     10021200     V070         
    11     021     0040     10021200     V070         
    3     021     0050     10021200     V070         
    and here is the desired output
    CALL     IPLINENO     LETTING      C0104              K0054              V070         
    021     0010     10021200      9,585                     11,420                                   8,010
    021     0020     10021200      1,000       1,100     900
    021     0030     10021200      1,000     1,100     1,320
    021     0040     10021200       17     5     11
    021     0050     10021200      5     3     3

    Here is the error message I am getting:
    RA-06550: line 22, column 43:
    PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier> <a double-quoted delimited-identifier>
    <a bind variable> << close current delete fetch lock insert
    open rollback savepoint set sql execute commit forall merge
    pipe

  • Query a stored procedure that exec's a dynamic query. Error Linked server indicates object has no columns

    I have a stored procedure that dynamically creates a pivot query.  The procedure works and returns the correct data.  Now I have a requirement to show this data in reporting system that can only pull from a table or view.  Since you can not
    create a dynamic query in a view I tried to do a select from using openquery. 
    Example 'Select * from OpenQuery([MyServername], 'Exec Instance.Schema.StoredProcedure')
    I get the error back "the linked server indicates the object has no columns".  I assume this is because of the first select statement that is stuffing the variable with column names. 
    CODE FROM PROCEDURE
    Alter PROCEDURE [dbo].[Procedure1]
    AS
    BEGIN
    SET NOCOUNT ON
    Declare @cols nvarchar(2000),
      @Tcols nvarchar(2000),
      @Sql nvarchar (max)
    select @cols = stuff ((
          Select distinct '], ['+ModelName + '  ' + CombustorName
           from CombustorFuel cf
           join Model m on cf.modelid = m.modelid
           join Combustors cb on cf.CombustorID = cb.CombustorID
           where cf.CombustorID > 0
           for XML Path('')
          ),1,2,'')+']'
    Set @Tcols = replace(@Cols, ']', '] int')
    --Print @Tcols   
    --Print @Cols
    Set @Sql = 'Select GasLiquid, FuelType, '+ @Cols +'
    from
     Select GasLiquid, FuelType, ModelName+ ''  '' +CombustorName ModelCombustor, CombFuelStatus+''- ''+CombFuelNote CombFuelStatusNote
      from Frames f
      join Family fa on f.Frameid = fa.frameid
      join Model m on fa.FamilyID = m.FamilyID
      join CombustorFuel cf on m.Modelid = cf.modelid
      Join Combustors c on cf.CombustorId = c.CombustorID
      join FuelTypes ft on cf.FuelTypeID = ft.FuelTypeID
      where cf.CombustorFuelID > 0
        and CombustorName <> ''''
     ) up
    Pivot
     (max(CombFuelStatusNote) for ModelCombustor in ('+ @Cols +')) as pvt
    order by FuelType'
    exec (@Sql)

    Then again, a good reporting tool should be able to do dynamic pivot on its own, because dynamic pivoting is a presentation feature.
    SSRS Supports dynamic columns: Displaying Dynamic Columns in SSRS Report
    SQL Reporting Services with Dynamic Column Reports
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014
    Displaying and reading are two very different things.
    #1) SSRS Needs a fixed field list on the input side to know what what to make available in the designer.
    #2) SSRS cant read "exec (@Sql)" out of a proc, even if there is a fixed number of columns (at
    least it can't use it to auto build the field list from the proc)
    I use dynamic SQL in my report procs on a fairly regular basis and I've found it easiest to simply dump
    the results of my dynamic sql into a temp table at the end of the procs and then select from the temp table.
    Basically, Erland is correct. Stop trying to pivot in the query and let SSRS (or whatever reporting software you're using) handle it with a Martix.
    Jason Long

  • Setting column count dynamically for a Group

    Hi Experts,
    i want to set the column count dynamically for a group.
    Thnks,
    Ramani.

    You probably mean you want to change the colCount value for a GridLayout (assigned to a Group), right?
    To change this property from a view controller method, you can
    - create a boolean context attribute "changeColCount" and set it to true in the controller method
    - check this flag in method wdDoModifyView(), access the GridLayout instance and change the colCount value
    - reset the flag afterwards
    Armin

  • Build dynamic query depending upon selection of table and columns

    Hi ,
    I want your views on following requirement :
    we r doing generic export to excel functionality .
    1.User will select multiple tables and according to tables ,columns on that table will select
    2.There can be multiple table
    3.depending upon column and table selection , we have to build dynamic query and execute .
    Please let me know is it possible .If yes then please tell me how to do above requirement.
    Thanks in advance

    Hi,
    Identifiers cannot be used as bind variables, query are parsed
    before evaluate bind variables. Identifiers like table name.
    For excel you can use some like this:
    SET MARKUP HTML ON ENTMAP ON SPOOL ON PREFORMAT OFF
    SPOOL test_xls.xls
    SELECT colum1||chr(9)||columN FROM tableName;
    or CSV:
    SELECT colum1|| ',' ||columN FROM tableName;
    SPOOL OFF
    SET MARKUP HTML OFF ENTMAP OFF SPOOL OFF PREFORMAT ON
    For construct the query i suggest to read "Dynamic SQL Statements":
    http://www.java2s.com/Tutorial/Oracle/0440__PL-SQL-Statements/0300__Dynamic-SQL.htm
    http://docs.oracle.com/cd/B28359_01/appdev.111/b28370/dynamic.htm
    http://docs.oracle.com/cd/B10500_01/appdev.920/a96590/adg09dyn.htm
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:227413938857
    --sgc                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Using 2 tables framing of dynamic query wherein columns are decided runtime

    Hi Team,
    I had a requirement could anyone help me out or suggest your views. we are using Adf faces as UIlayer and Toplink for dataaccess. In that we had 2 tables systemdefinedTable and userdefinedTable which has one-to-one relation. Userdefinedtable has columns col1,col2,col3.......col50 and this comes at runtime from xml like col1 as Lastname,col2 as firstname.
    Now we need to generate a dynamic query that joins the systemdefinedTable and userdefinedTable to produce the result for the UI layer. Now suppose if the xml has 2 cols tag.
    The dynamic query may look like this:
    Select S.ID, S.NAME, S.STATUS, U.COL1 as FirstName, U.COL2 as LastName
    From userdefinedTable U, systemdefinedTable S
    Where S.QID = U.QID
    Next if the xml has 3 more column tags then COL1,COL2,COL3 ...like wise columns will be decided runtime..So please share your views or any related blogs to achieve this.
    Thanks in Advance for your help.

    Hello,
    If you are using TopLink and need dynamically generated queries, why not use TopLink Expressions for your queries, and return java objects back. Then you can display which ever fields from the fully populated objects that you need.
    See the docs for TopLink queries here:
    http://docs.oracle.com/cd/E17904_01/web.1111/b32441/qryun.htm#autoId28
    A simple example returning all systemdefinedObjects would be:
    ReadAllQuery query = new ReadAllQuery(systemdefinedObject.class);
    query.addJoinedAttribute(query.getExpressionBuilder().get("user"));
    Collection<systemdefinedObject> results = session.executeQuery(query);
    This allows populating the cache and for caching the statements and the query results.
    But I'm not sure exactly what you are after.
    Best Regards,
    Chris

  • Dynamic Query Row Count

    Dear HTML Gurus,
    I have a SQL Query Region that returns/executes a dynamic SQL Query. Based on the number of rows a particular query returns I want to hide or show a different HTML region. I have searched all over for this kind of functionality and have come up with absolutely nothing. I would think that this would be integrated into HTMLDB because Pagination shows the total number of rows returned. Any help or direction would be wonderful.
    Thanks,
    James

    This is how I would do it:
    1. create an (hidden) item,
    2. create a computation for that item and run it after submit. This computation could be a function returning the rowcount value into your (hidden) item - rowcount of my dynamic sql.
    If my dynamic query is to big to be entered into the computation "container", which accepts only a limited number of characters, then I would slightly change my approach:
    3. I would create a function in my schema and and call this function from the computation level - either through a simple sql query (select function(in parameter) from dual) or, again through a function returning a number.
    I tested this and it worked.
    Denes Kubicek

  • Dynamic Query to display a page of records at a time

    I need some help creating procedure with a dynamic query that will query a table and pass out a certain number of records (like records 101 - 200 of 20,000). This procedure will receive the column names, table name, where clause, page number and number of records per page. It will then pass back the requested records to be displayed on a PHP page.
    Pseudo Code:
    Select Dynamic_Columns, ROWNUM
    Into Dynamic_Pl_Sql_Table
    From Dynamic_Table
    Where Dynamic_Where_Clause
    Total_Records_Out := Dynamic_PL_Sql_Table.Count
    Modulus := Mod(Total_Records_Out, Total_Records_Per_Page_In)
    Total_Pages_Out := (Total_Records_Out - Modulus) / Total_Records_Per_Page_In
    If Modulus > 0 Then
    Total_Pages_Out + 1
    End If
    Row_Start = Page_Number_In * Total_Records_Per_Page_In
    Row_End = Row_Start + Total_Records_Per_Page_In
    Results_Out = Dynamic_Pl_Sql_Table(Row_Start ... Row_End)
    Any help with this will be appreciated!

    Maybe this will help you
    1) If the Serial is 0 then page break
    2) total_rows gives you total number of rows selected.
    3) you can apply where clause to this and it will give you appropriate records.
    select empno, ename, sal, 
    mod(row_number() over (order by null),5) serial,
    count(*) over () tot_rows from emp ed
         EMPNO ENAME             SAL     SERIAL   TOT_ROWS
          7369 SMITH             800          1         14
          7499 ALLEN            1600          2         14
          7521 WARD             1250          3         14
          7566 JONES            2975          4         14
          7654 MARTIN           1250          0         14
          7698 BLAKE            2850          1         14
          7934 MILLER           1300          2         14
          7788 SCOTT            3000          3         14
          7839 KING             5000          4         14
          7844 TURNER           1500          0         14
          7876 ADAMS            1100          1         14
          7900 JAMES             950          2         14
          7902 FORD             3000          3         14
          7782 CLARK            2450          4         14
    14 rows selected.SS

  • How to create custom BOL object for dynamic query in CRM 7.0

    Hi,
    Could anyone please explain me with steps that how to create the custom BOL object for dynamic query in CRM 7.0, I did it in previous version but its throwing exception when i try to create the object of my dynamic query class. I just defined the entry of my in crmv_obj_btil to create the dynamic query BOL object. do i need to do any other thing also to make it work?
    Regards,
    Kamesh Bathla
    Edited by: Kamesh Bathla on Jul 6, 2009 5:12 PM

    Hi Justin,
    First of thanks for your reply, and coming to my requirement, I need to report the list of items which are there in the dynamic select statement what am getting from the DB. The select statement number of columns may vary in my example for different countries the select item columns count is different. For US its '15', for UK it may be 10 ...like so, and some of the column value might be a combination or calculation part of other table columns (The select query contains more than one table in the from clause).
    In order to execute the dynamic select statement and return the result i choose to write a function which will parse the cursor for dynamic query and then iterate the values and construct a Type Object and append it to the pipe row.
    Am relatively very new for these sort of things, welcome in case of any suggestions to make it simple (Instead of the function what i thought to work with) also a sample narrating the new procedure will be appreciated.
    Thanks in Advance,
    mallikj2.

  • Dynamic query and Open Cursor fetch into ??

    Hi;
    I think we took the wrong turn some were... because looks like a dead end...
    What I need to do:
    Create a procedure to compare two generic tables in diferente databases and find rows that have diferent data.
    (No restritions on what tables it might compare)
    What I have done:
    CREATE OR REPLACE PROCEDURE COMPARE_TABLES_CONTENT_V3(
    tableName_A IN VARCHAR2, tableName_B IN VARCHAR2, filter IN VARCHAR2) AS
    -- Get all collumns present in [TableName_A]
    -- This is necessary to create a dynamic query
    select column_name bulk collect
    into v_cols1
    from all_tab_columns
    where table_name = v_tab1
    and owner = nvl(v_own1, user)
    order by column_id;
    -- If there is no columns in table A ... them no need to proceed
    if v_cols1.count = 0 then
    dbms_output.put_line('[Error] reading table ' || tableName_A ||
    ' collumns information. Exit...');
    return;
    end if;
    -- Collect Collumns information by ',' separated, for the query
    for i in 1 .. v_cols1.count loop
    compareCollumns := compareCollumns || ',' || v_cols1(i);
    end loop;
    -- Create the query that gives the diferences....
    getDiffQuery := 'select ' || compareCollumns ||
    ' , count(src1) CNT1, count(src2) CNT2 from (select a.*, 1 src1, to_number(null) src2 FROM ' ||
    tableName_A ||
    ' a union all select b.*, to_number(null) src1, 2 src2 from ' ||
    tableName_B || ' b) group by ' || compareCollumns ||
    ' having count(src1) <> count(src2)';
    Whats the problem?
    I'm lost...I can access the query using debugging on the oracle procedure... and run it OK on a new SQL window. No problem here... its perfect.
    But I dont know how to access this information inside the procedure, I need to format the information a bit...
    I try a cursor...
    open vCursor for getDiffQuery;
    fetch vCursor into ??????? -- Into what... query, columns and tables is all dynamic...
    close vCursor;
    Any ideas..

    Making the issue more simple....
    At this point I have a oracle procedure that generates a dynamic sql query, based on the table names passed by parameter.
    getDiffQuery := 'select ' || compareCollumns || (.....)
    end procedure;
    This ''getDiffQuery'' contains a query that gets the diferences in the tables. (Working fine)
    I would like to access this information in the same procedure.
    I cant use cursor because the table, columns... actualy all is dynamic based on the generated query:( !

  • Help on performance with dynamic query

    Hi All,
      We are using SQL Server 2008R2. In our one of report we are using Dynamic query and it is taking more time to retrieve the data. to retrieve 32 records it is taking 13-15 secs. In my observation in a table variable, created more than 60 columns. In
    the SP called one more sp with insert statement.
    Please let me know how i can improve performance of the SP.
    I know that i have to provide the SP  for observation but unfortunately I cannot provide the SP. Please guide me how i can achieve this .
    I tried with temp tables by creating indexes on temp tables but i couldn't find improvement in performance. 
    Waiting for valuable replies.

    First of all a "dynamic query" is not "a query" - it is a multitude of them. Some of them may be fast, others may be slow.
    There is of course no way we can give specific suggestions without seeing the code, the table and index definitions etc.
    We can only give the generic suggestions. As for the code, make sure that you are using parameterised SQL and you are not building a complete SQL string with parameters and all. If nothing else, this helps to make the code more readable and maintainable.
    It also protects you against SQL injection. And it also helps to prevent performance issue due to implicit conversion.
    You will need to look at the query plan to see where the bottlenecks may be. You should look at the actual query plan. Note that the thickness of the arrows are more relevant than the percentages you see; the percentages are only estimates, and estimates
    are often off. Next step is to see if you can add indexes to alleviate the situation. You should also analyse if there are problems in the query, for instance indexed columns that are entangled in expression. If you are using views, make sure that you don't
    have views built on top of views etc. This can often result a table appearing multiple times in a query, when one would be enough.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to create a dynamic RTF report which creates dynamic columns based on dynamic column selection from a table?

    Hi All,
    Suppose I have table, whose structure changes frequently on daily basis.
    For eg. desc my_table gives you following column name on Day 1
    SQL > desc my_table;
    Output
    Name
    Age
    Phone
    On Day 2, two more columns are added, viz, Address and Salary.
    SQL > desc my_table;
    Output
    Name
    Age
    Phone
    Address
    Salary
    Now I want to create an Dynnamic RTF report which would fetch data from ALL columns from my_table on daily basis. For that I have defined a concurrent program with XML as output type and have attached a data template/data definition to it which takes in XML as input and gives final output of conc program in EXCEL layout. I am able to do this for constant number of columns, but dont know how to do it when the number of columns to be displayed changes dynamically.
    For Day 1 my XML file should be like this.
    <?xml version="1.0" encoding="UTF-8"?>
    <dataTemplate name="XYZ" description="iExpenses Report" Version="1.0">
    <dataQuery>
    <sqlStatement name="Q2">
    <![CDATA[
    SELECT Name
    ,Age
    ,Phone
    FROM my_table
    ]]>
    </sqlStatement>
    </dataQuery>
    <dataStructure>
    <group name="G_my_table" source="Q2">
      <element name="Name" value="Name" />
      <element name="Age" value="Age" />
      <element name="Phone" value="Phone" />
    </group>
    </dataStructure>
    </dataTemplate>
    And my Day 1, EXCEL output from RTF template should be like this.
    Name     Age     Phone
    Swapnill     23     12345
    For Day 2 my XML file should be like this. With 2 new columns selected in SELECT clause.
    <?xml version="1.0" encoding="UTF-8"?>
    <dataTemplate name="XYZ" description="iExpenses Report" Version="1.0">
    <dataQuery>
    <sqlStatement name="Q2">
    <![CDATA[
    SELECT Name
    ,Age
    ,Phone
    ,Address
    ,Salary
    FROM my_table
    ]]>
    </sqlStatement>
    </dataQuery>
    <dataStructure>
    <group name="G_my_table" source="Q2">
      <element name="Name" value="Name" />
      <element name="Age" value="Age" />
      <element name="Phone" value="Phone" />
      <element name="Address" value="Address" />
      <element name="Salary" value="Salary" />
    </group>
    </dataStructure>
    </dataTemplate>
    And my Day 2, EXCEL output from RTF template should be like this.
    Name     Age     Phone     Address     Salary
    Swapnill     23     12345         Madrid     100000
    Now, I dont know below things.
    Make the XML dynamic as in on Day 1 there must be 3 columns in the SELECT statement and on Day 2, 5 columns. I want to create one dynamic XML which should not be required to be changed if new columns are added in my_table. I dont know how to create this query and also create their corresponding elements below.
    Make the RTF template dyanamic as in Day1 there must 3 columns in EXCEL output and on Day 2, 5 columns. I want to create a Dynamic RTF template which would show all the columns selected in Dynamic XML.I dont know how the RTF will create new XML tags and how it will know where to place it in the report. Means, I can create RTF template on Day 1, by loading XML data for 3 columns and placing 3 XML tags in template. But how will it create and place tags for new columns on Day 2?
    Hope, you got my requirement, its a challenging one. Please let me know how I can implement the required solution using RTF dynamically without any manual intervention.
    Regards,
    Swapnil K.
    Message was edited by: SwapnilK

    Hi All,
    I am able to fulfil above requirement. Now I am stuck at below point. Need your help!
    Is there any way to UPDATE the XML file attached to a Data Definition (XML Publisher > Data Definition) using a standard package or procedure call or may be an API from backend? I am creating an XML dynamically and I want to attach it to its Data Definition programmatically using SQL.
    Please let me know if there is any oracle functionality to do this.
    If not, please let me know the standard directories on application/database server where the XML files attached to Data Definitions are stored.
    For eg, /$APPL_TOP/ar/1.0/sql or something.
    Regards,
    Swapnil K.

Maybe you are looking for