Building a dynamic query

I have a need to build a truly dynamic query, that would be able to take online form input and create a query that would handle data requests like, How many employees earn less than #some salary, have a masters degree, and speak chinese.  or show me all the employees in org A that are vets.
A true ad hoc query tool. 
the back end is oracle 11g, the database  contains about 8 or 9 tables all total there about 500 records that will be searched. we are running CF7.
I just started kicking this around today so I am open for Ideas.  add filters in the where clause, i got that,   start with  1=1 and use conditional statements to add filters as necessary.  setting up the Select and From statements, need help there.
Since this is a small db, I thout about, but scrapped, making a super-view to query from.
your thoughts and suggestions would be greatly appreciated.
thanks
jb

What about something like this:
1) Determine what tables are going to be involved (visual GUI/drag & drop interface for the users?)
2) Have a table that defines the relationship between the other tables in your database - once the table selection is made by the user, you can query this table to determine what columns you are going to join on.  Obviously this won't allow you complete customization but it would work for the scenarios you describe.
3) Use your database system properties to retrieve the field names from your included tables
4) Allow your users to add "filters" based on the fields retrieved in (3)
e.g. You could use an interface to allow users to add a filter, where you display a list of fields from your tables and allow them to apply a simple filter to them - keep it simple (=, !=, >, <)
for bonus points, you could limit the options based on the field type (checkboxes for bit fields, etc)
sanitize the user input - find a SQL-safe reg exp script to handle any unwanted characters (I'm looking at you apostrophe).
5) Don't try an support aggregates if you don't need to - users can load the results into excel and manipulate them to their hearts content.
6) Build your SQL using the selections made by the user.  Import all records from your joined tables.  Use the table from (2) to determine which fields they join on.  and build your where clause using the filters the user created in steap (4).  Again, be sure anything not explicitly set by the system is sanitized prior to making its way into the SQL.
7) Execute() your SQL inside a CF query.  Expect pretty poor performance, since most SQL databases won't optimize a query plan from a dynamic SQL evaluation.
You could build this as a multi-step wizard in CF, but it would be pretty flashy as a jQuery/web service based application.

Similar Messages

  • Table name stored in another table and how to Build the Dynamic Query

    TblMasterTable
    Id
    Unqid
    Tbl_TemplateNameid
    Tbl_Template1
    Unqid
    Field1
    Filed2
    Tbl_Template2
    Unqid
    Field1
    Filed2
    Filed3
    Tbl_Template3
    Unqid
    Field1
    Filed2
    Filed3
    Filed4
    Filed5
    TblMasterTable contains the reference for the table names.
    TblMasterTable contains the data
    1 12     Tbl_Template1
    2 22     Tbl_Template2
    3 12     Tbl_Template1
    4 343 Tbl_Template3
    I want to build the query to retrieve all the Template table records based on the TblmasterTable data for a given id.

    This is possible but you need to understand the performance implications of Dynamic SQL before proceeding with this approach.
    <br>
    use this logic:<br>
    declare sqlstring varchar2(500):=null <br>
    select 'select stuff from '|| tbl_templatenameid into sqlstring from MasterTable where id=someid;<br>
    execute immediate sqlstring;
    <br>
    <br>
    I have really seen very few cases where this approach is justified.
    <br>
    <br>
    Dave<br>
    lehr.servehttp.com

  • How ca n i build a dynamic query in a cursor

    i have a cursor in a procedure. it runs some sql query. i want to build a part of this query dynamically based on the parameters passed to this procedure.how should i do thatnow the cursor is before the begin end structure and if i have to build a query whose return results are to be processed then i have to write that in a cursor and i cannot write a cursor inside a begin end(that's my understanding) and only way to build a query is to build it in a begin end . i think reference cursors can be used to accomplish this task. can someone guide me with this.thnx in advance.

    This is straightforward programming logic....
    CREATE OR REPLACE FUNCTION my_qry
       (p1 IN VARCHAR2 := NULL, p2 IN VARCHAR2 := NULL)
       RETURN sys_refcursor
    IS
       stmt VARCHAR2(32767) :='select creation_date from mytable';
       clause1 VARCHAR2(32767) := 'app_id=';
       clause2 VARCHAR2(32767) := 'ticket_number=';
       rc sys_refcursor;
    BEGIN
       CASE
          WHEN p1 IS NOT NULL AND p2 IS NOT NULL
          THEN
             open rc for stmt||
                 ' WHERE '||clause1||':1 AND '||
                 clause2||':2' USING p1, p2;
          WHEN p1 IS NOT NULL AND p2 IS NULL
          THEN
             open rc for stmt||
                 ' WHERE '||clause1||':1 ' USING p1;
          WHEN p1 IS NULL AND p2 IS NOT NULL
          THEN
             open rc for stmt||
                 ' WHERE '||clause2||':1 ' USING p2;
          ELSE
             open rc for stmt;
        END CASE;
        RETURN rc;
    END;
    [pre]
    Cheers, APC                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Dynamic Query and default run-time values

    I am trying to build a dynamic query within dreamweaver and
    retain access from the bindings panel.
    here is a simple pseudo-query I want to expand on.
    "SELECT object FROM objects_table WHERE widget_number =
    widgets"
    widgets is set up as a variable with a run-time value that
    relates to $_GET['widgets']
    this works fine but now i want to expand on this so the query
    returns all results if $_GET['widgets'] is undefined. I was hoping
    I could set the default value for widgets to equal widget_number so
    I would get....
    "SELECT object FROM objects_table WHERE widget_number =
    widget_number" but the runtime query is actually
    "SELECT object FROM objects_table WHERE widget_number =
    'widget_number' " which obviously doesn't work.
    I can alter the query manually from the code view but then I
    lose access to the bindings panel as dreamweaver doesn't parse the
    query properly.
    Any pointers?
    Thanks in advance
    - Andrew

    Andy Millne wrote:
    > That will work fine server-side yeah but dreamweaver
    cannot parse the code at
    > design time so by altering the code in this way you lose
    access to the bindings
    > panel and all the server behaviours that depend on the
    recordset have
    > exclamation marks alongside.
    This is simply a question of organizing your workflow. As you
    have
    discovered, Dreamweaver no longer recognizes a recordset if
    you make
    changes to the basic structure of the code. The answer is to
    use
    Dreamweaver to construct your page using an unaltered
    recordset. Once
    the design stage is complete, make the changes required by
    inserting
    your conditional statement. Yes, the fieldnames disappear
    from the
    Bindings panel, and you get exclamation marks in the Server
    Behaviors
    panel, but that's not important. If you need to restore them
    for any
    reason, just wrap the changes in /* */ comments. Remove the
    comments
    when you have finished.
    David Powers, Adobe Community Expert
    Author, "The Essential Guide to Dreamweaver CS3" (friends of
    ED)
    Author, "PHP Solutions" (friends of ED)
    http://foundationphp.com/

  • Dynamic Query Data issue...Apex Charts

    Database version and APEX version are in the tags...11g  and4.1.2
      I have data in this format
    NODE_NAME
    REPORT_DATE
    STORAGE_AMOUNT_ALLOC
    Anole
    01/01/2013
    3175
    Fiji
    01/01/2013
    0
    Anole
    02/01/2013
    3175
    Fiji
    02/01/2013
    0
    Anole
    04/01/2013
    3276
    Fiji
    04/01/2013
    0
    Anole
    05/01/2013
    3276
    Fiji
    05/01/2013
    0
    Anole
    06/01/2013
    3276
    Fiji
    06/01/2013
    0
    I've build a Dynamic query which returns:
    SELECT NULL LINK,report_date DATIME,decode(NODE_NAME,'Anole',STORAGE_AMOUNT_ALLOC)"Anole",decode(NODE_NAME,'Fiji',STORAGE_AMOUNT_ALLOC)"Fiji" FROM STORAGE_REPORTS WHERE report_date between to_date('01-JAN-2013','DD-MON-YYYY') and to_date('01-JUN-2013','DD-MON-YYYY') and (INSTR(':Anole:Fiji:', ':'||NODE_NAME||':') > 0) ORDER BY report_date ASC
    The resultant data is
    LINK
    DATIME
    Anole
    Fiji
    01/01/2013
    3175
    01/01/2013
    0
    02/01/2013
    3175
    02/01/2013
    0
    04/01/2013
    3276
    04/01/2013
    0
    05/01/2013
    0
    05/01/2013
    3276
    06/01/2013
    3276
    06/01/2013
    0
    When I put the above query to the chart it give me accurate series with one..however when I add a second NODE to the query it completly hacks the chart. I have a feeling this is because I have repeating dates and it doesn' know how to handle this. So I'm wondering how I get rid of the repeating dates. and make them all one row with columns for each series.
    Thanks
    Rob

    apex version?  database version?
    if you're on 11g, it sounds like you want the PIVOT command.
    you should also post a simple CREATE TABLE and a few INSERT statements so others can test.
    select null link
      ,report_date as datime
      ,"Anole", "Fiji"
    from ( select REPORT_DATE, NODE_NAME, STORAGE_AMOUNT_ALLOC
      from STORAGE_REPORTS
    PIVOT (
      sum( storage_amount_alloc )
      for (node_name)
      in ( 'Anole' "Anole", 'Fiji' "Fiji" ) -- rename columns here
    where report_date between to_date('01-JAN-2013','DD-MON-YYYY') and to_date('01-JUN-2013','DD-MON-YYYY')
    order by report_date asc

  • Dynamic Query in Report Builder

    HI
    I have a doubt:
    I need to receive a parameter in my report and I need this parameter in the query, that means, I need to create a dynamic query depending on the value that I receive in one of the parameters that has my report.
    I tried to use the resource of Searching by Reference Cursor tool, it is a blue circle in the Data Model View of Report Builder.
    When I click this tool, I have an initial code, It is:
    function QR_1RefCurDS return <RefCurType> is
    begin
    end;
    In PL/SQL I tried to create to test and to play, this code:
    Note: If you want to try only to test, it is simple and works:
    create or replace package TEST_REFCURTYPE as
    type refcurtype is ref cursor;
    function TEST_REFCURTYPE (P_DATE_TO nvarchar2) return refcurtype;
    end;
    create or replace package body TEST_REFCURTYPE as
    function TEST_REFCURTYPE (P_DATE_TO nvarchar2)
    return refcurtype is
    refcur refcurtype;
    mysql varchar(1000);
    begin
    If P_DATE_TO is not null then
    mysql := 'select '''|| P_DATE_TO ||''' from dual';
    else
    mysql := 'select sysdate from dual';
    end if;
    open refcur for mysql;
    return refcur;
    end;
    end;
    The problem is to pass this example of code to the function QR_1RefCurDS, I do not have a place to make reference to the type:
    type refcurtype is ref cursor;
    I tested the Unit Program in the Report Builder but it did not work, because all the code I try to write and create, for example in the Event BEFORE REPORT, it opens  Funcion( ) …., and I can not make reference to the type refcurtype inside a Function( ).
    Would you help me please?
    Or there is another way to make a dynamic query in the Report Builder?
    Sorry for my English, I am a Brazilian living in Spain.

    Hi,
    you can use lexical parameters in your queries. Instead of a ":" use in the query before the parameter a "&". Then the parameter stands for a part of the query and not for a value (Bind parameter). In the before report trigger you can set this parameters. They can contain parts of SQL like order or where. Make sure that the default value for this lexical parameters are set to get a valid query.
    SELECT ENAME, &p_column as COL2 FROM EMP &p_order
    and in the trigger something like
    IF :p_which_column = 1 THEN
    :p_column := 'SAL'
    ELSE
    Saludos
    Rainer

  • Geting ORA 936 -while building dynamic query in for loop.

    HI,
    I hav written a SP and its compiled and giving me the results for the data I am quering but giving ORA936 - missing expressin and giving ORA 6512 at 2 lines. Please help me me out where I am going wrong.
    CREATE OR REPLACE TYPE LIST as VARRAY(5000) of NUMBER;
    CREATE OR REPLACE PROCEDURE test( V_id IN LIST,
    v-fdate IN DATE,
    v-tdate IN DATE,
    v_flg IN CHAR)
    AS
    TYPE opfld IS RECORD (
    FID TAB.ID%TYPE,
    FCURR TAB.CURR %TYPE,
    FCNT TAB.CNT%TYPE,
    FTOT TAB.TOT%TYPE );
    TYPE OPLIST IS REF CURSOR;
    Rc oplist;
    Edtab opfld;
    Selstr VACHAR2(200);
    Whstr1 VACHAR2(200);
    Whstr2 VACHAR2(200);
    Whstr3 VACHAR2(200);
    Whstr VACHAR2(200);
    Grpstr VACHAR2(200);
    Andstr VACHAR2(200);
    Fullstr VACHAR2(200);
    BEGIN
    Selstr := ‘SELECT col1,col2,sum(col3),sum(col4) from tab1 ’;
    Whstr1 := ‘ WHERE tdate BETWEEN TO_DATE(‘||’’’’||vfdate||’’’’||’)’;
    Whstr2: = ‘ AND TO_DATE(‘||’’’’||vtdate||’’’’||’)’;
    Whstr := whstr1||whstr2;
    Grpstr := ‘GROUP BY col1,col2’;
    IF v_flg IS NOT NULL THEN
    Whstr3 := whstr||’AND FLAG = ‘||v_flg;
    else
    Whstr3 := whstr ;
    END IF;
    FOR I IN 1..id.COUNT LOOP
    BEGIN
    Andstr := ‘ AND id =’|| v_id(i);
    Whstr := whstr3 || andstr ;
    Fullstr := selstr||whstr||grpstr;
    OPEN rc for fullstr;
    LOOP
    FETCH rc into edtab
    EXIT when rc%NOTFOUND;
    END LOOP;
    Andstr := ‘’;
    Whstr :=’’;
    END; ---BEGIN of FOR loop
    END LOOP; -- for end
    CLOSE rc;
    END; -- proc end
    Created above SP and its compiled. When I try to execute the SP with below code I am getting--
    DECLARE
    V_t LIST;
    BEGIN
    V_t:= LIST();
    V_t.EXTEND(10);
    V_t(1) := 10;
    V_t(2) := 20;
    Test(v_t,’25-APR-2012’,’30-APR-2012’,’Y’);
    END;
    The SP is building correct dynamic querry and its getting executed for id = 10 and 20, giving the correct results but though I defined only 2 ids while executing and written FOR lOOP upto ID.COUNT its building query for third time and that time its not getting id, so for the third time the last part of where clause is built like
    SELECT.....
    WHERE....
    AND id = (its taking blank here)
    GROUP BY ...;
    and thus its giving me ORA 936 missing expression and ORA 06152 at line of RECORD TYPE declaration and line of OPEN rc for fullstr;
    ERROR at line 1
    ORA 00936 misssing expresiion
    ORA 006152 at line 9
    ORA 006512 at line 87
    I hav put DBMS_OUTPUT statements @ every build of dynamic wuery and its correct. here I have not copid the code I hav typed hereso not wriiten DBMS_OUTPUT.
    I tried lot of ways redefining Andstr := ‘’;
    Whstr :=’’; after for endloop but its giving the same error. is this because I am using varray? If am providing 2 ids in anonymous block then how its building query for third blank ID value.
    Please help me out here..
    Thanks a lot..

    >
    I hav written a SP and its compiled and giving me the results for the data I am quering
    >
    Then you should have posted the one that compiles and gives you results.
    The code you posted will not compile without errors. Edit your original post and provide the corrected code.
    When you do please add \ tags on the line before and after the code to preserve formatting. See the FAQ for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • 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]

  • Dynamic Query

    Dynamic Query
    When I run the following dynamic query in the stored procedure and try to build the report then I get the following error Rep:1401 Fatal PL/SQL error occured, Ora-00936 Missing expression. When I am generating the report standalone using the following query , everything is working fine but in Stored procedure , it's giving me the above error, pls help.
    create or replace package REP_DELIVERY_LOC_STATISTICS is
    TYPE REP_DELIVERY_LOC_STAT_rec IS RECORD(
    p_coordinating_facility_id sis_education_pgm_session.coordinating_facility_id%TYPE,
    p_PSE_MUNICIPALITY_ID pse_education_pgm_session.PSE_MUNICIPALITY_ID%TYPE,
    p_pse_education_pgm_session_id sis_education_pgm_session.pse_education_pgm_session_id%TYPE,
    p_course_session_id course_session.course_session_id%TYPE);
    TYPE REP_DELIVERY_LOC_STAT_cur IS REF CURSOR RETURN REP_DELIVERY_LOC_STAT_rec;
    Type REP_DELIVERY_LOC_STAT_cur_Dyn is REF CURSOR;
    FUNCTION REP_DELIVERY_LOC_STATISTICS(p_college_id IN pse_education_pgm_session.delivery_institution_id%TYPE,
    p_start_date IN pse_education_pgm_session.session_strt_dte%TYPE,
    p_end_date IN pse_education_pgm_session.session_strt_dte%TYPE,
    p_coord_facility_join IN varchar2) return REP_DELIVERY_LOC_STAT_cur_Dyn;
    end REP_DELIVERY_LOC_STATISTICS;
    create or replace package body REP_DELIVERY_LOC_STATISTICS is
    FUNCTION REP_DELIVERY_LOC_STATISTICS(p_college_id IN pse_education_pgm_session.delivery_institution_id%TYPE,
    p_start_date IN pse_education_pgm_session.session_strt_dte%TYPE,
    p_end_date IN pse_education_pgm_session.session_strt_dte%TYPE,
    p_coord_facility_join varchar2) return REP_DELIVERY_LOC_STAT_cur_Dyn IS
    REP_DELIV_LOC_STAT_CUR_Dyn_Q REP_DELIVERY_LOC_STAT_cur_Dyn;
    BEGIN
    OPEN REP_DELIV_LOC_STAT_CUR_Dyn_Q FOR
    'SELECT distinct
    seps.coordinating_facility_id,
    peps.PSE_MUNICIPALITY_ID,
    seps.pse_education_pgm_session_id,
    cs.course_session_id
    FROM pse_education_pgm_session peps,
    sis_education_pgm_session seps,
    course_session cs,
    facility fac,
    desc_sis_reporting_area depa,
    desc_sis_reporting_type dept,
    pse_education_program pep
    WHERE peps.delivery_institution_id (+) = ' || p_college_id
    || ' and peps.session_strt_dte between ' ||p_start_date||' and ' || p_end_date
    || ' and seps.coordinating_facility_id = fac.facility_id (+)
    and seps.pse_education_pgm_session_id (+) = peps.pse_education_pgm_session_id
    and seps.pse_education_pgm_session_id = cs.pse_education_pgm_session_id (+)
    and pep.pse_education_program_id = peps.pse_education_program_id
    and dept.desc_sis_reporting_area_id = depa.desc_sis_reporting_area_id
    and pep.desc_sis_reporting_type_id = dept.desc_sis_reporting_type_id
    and dept.desc_sis_reporting_area_id = depa.desc_sis_reporting_area_id
    and fac.desc_facility_id in (2,3)' || NVL (p_coord_facility_join, '1=1');
    return REP_DELIV_LOC_STAT_CUR_Dyn_Q;
    END;
    end REP_DELIVERY_LOC_STATISTICS;

    I would sugest to grab a book like
    Inside Microsoft SQL Server 2008 T-SQL Querying (chapter 12 - Graphs, Trees, Hierarchies and Recursive Queries) or
    Joe Celko's Trees and Hierarchies in SQL for Smarties to get familiar with how model hierarchies using SQL.
    What is the meaning of the asterisks in the path?
    Here is a dirty example using the Adjacency List model.
    SET NOCOUNT ON;
    USE tempdb;
    GO
    CREATE TABLE dbo.T1 (
    id int NOT NULL UNIQUE CLUSTERED,
    name varchar(50),
    rootid int NULL
    INSERT INTO dbo.T1 (id,name,rootid)
    SELECT 1, 'animals', NULL
    UNION ALL
    SELECT 2, 'mamal', 1
    UNION ALL
    SELECT 3, 'cephalopod mollusc', 1
    UNION ALL
    SELECT 4, 'salt water fish', 1
    UNION ALL
    SELECT 5, 'fresh water fish', 1
    UNION ALL
    SELECT 6,'whale', 2
    UNION ALL
    SELECT 7,'pirana', 5
    UNION
    SELECT 8,'shark', 4
    UNION
    SELECT 9, 'octopus', 3;
    GO
    WITH Tree AS (
    SELECT
    id, name, rootid,
    CAST('/' + [name] + '/' AS varchar(900)) AS mat_path
    FROM
    dbo.T1
    WHERE
    rootid IS NULL
    UNION ALL
    SELECT
    C.id, C.name, C.rootid, CAST(P.mat_path + C.name + '/' AS varchar(900))
    FROM
    Tree AS P
    INNER JOIN
    dbo.T1 AS C
    ON P.id = C.rootid
    SELECT
    FROM
    Tree
    ORDER BY
    mat_path;
    GO
    DROP TABLE dbo.T1;
    GO
    Excuse my poor knowledge of zoology or animal biology.
    AMB
    Some guidelines for posting questions...
    AYÚDANOS A AYUDARTE, guía básica de consejos para formular preguntas

  • How to enhance Dynamic Query Object TerrSearch (Territory Management)?

    Hello Friends,
    In the TerrSearch dynamic query object, There are 2 fields Territory_ID and Level_ID. Now i have a requirement to Enhance the Search object using the new field called TERRITORY PATH ID. using which we can search all the entities not only for the terrritory level which we have selected (for example we have assigned the value '01' to LEVEL_ID) but also all the below territory levels of selected territory level.
    If we enhance the search object structure CRMST_TMIL_SEARCH (structure of TerrSearch object) using AET to add the Z field called TERRITORY_PATH_ID then which is the suitable BADI where we can add the necessary code to select all the entities based on all the territory levels below the selected territory level.
    Please guide me friends how to enhance the TerrSearch object.

    Hi friend,
    Try using MACRO and dynamic WHERE condition.
    Group simialr Select statements under a Macro.
    Build a dynamic where by checking conditions
    Call macro passing dynamic where condition.
    TABLES afpo.
    DATA: str TYPE string.
    *Macro definition
    DEFINE operation.
      select single *
           from afpo into afpo
           where (&1).    " Dynamic condition
    END-OF-DEFINITION.
    *Build dynamic WHERE by checking some conditions
    *If conditon 
    CONCATENATE 'AUFNR = ''000000700008''' 'AND POSNR = ''0001''' INTO str SEPARATED BY space.
    *Else
    CONCATENATE 'AUFNR = ''000000700008''' 'AND POSNR = ''0002''' INTO str SEPARATED BY space.
    *Endif.
    *Call Macro passing dynamic WHERE condition
    operation str.

  • Unable to retrieve results using dynamic query

    Hi Experts,
    I have created a custom table and have created a custom bol to integrate it with web ui. I have redefined the dynamic query result method of genil layer. I find the data into LT_RESULT but when I invoke the root list method the LR_OBJECT does not contain the values.
    Please see below the code that I have written.
    ====================================
    METHOD IF_GENIL_APPL_INTLAY~GET_DYNAMIC_QUERY_RESULT.
    DATA: LR_OBJECT TYPE REF TO IF_GENIL_CONT_ROOT_OBJECT,
    LT_RESULT TYPE TABLE OF ZCRMST_XXXX,
    LV_DYN_WHERE TYPE STRING,
    LV_LEN TYPE I,
    LS_RANGE TYPE SELOPTOBJ.
    DATA: LT_XXXX TYPE TABLE OF SELOPTOBJ,
    LT_YYYY TYPE TABLE OF SELOPTOBJ.
    FIELD-SYMBOLS: <LFS_RESULT> TYPE ZCRMST_XXXX,
    <LFS_SELECTION_RANGE> TYPE GENILT_SELECTION_PARAMETER.
    decomposition of selection parameters and build a dynamic where condition
    SELECT * FROM ZXXXX INTO TABLE LT_RESULT[].
    CHECK LINES( LT_RESULT[] ) > 0.
    LOOP AT LT_RESULT[] ASSIGNING <LFS_RESULT>.
    LR_OBJECT = IV_ROOT_LIST->ADD_OBJECT( IV_OBJECT_NAME = 'Root'
    IS_OBJECT_KEY = <LFS_RESULT>-XXXX ).
    CHECK LR_OBJECT IS BOUND.
    LR_OBJECT->SET_QUERY_ROOT( ABAP_TRUE ).
    ENDLOOP.
    ENDMETHOD.
    ==================================================
    Thanks in advance,

    Hi,
    Please check your get_objects method of the genil class. I made some changes to my implementation of get_objects method and it fixed the problem.
    Regards,
    Sandeep

  • How to use dynamic query for this ??

    hi , i am new to ABAP. i got a requirement to write  dynamic query for the following code.
    kindly address. two set of queries are same.but condition is different.
    .IF p_psd EQ ' '.
    *C--End of change DF 1232137- (Transport # :CIDK980530 )
    *C--FETCH THE Deliverd Quantiity and Material Number
        SELECT aufnr "ORDER number
               wemng "Quantity of goods received for the order item
               matnr "MATERIAL NUMBER
               pwerk "PLANT
               dauat "Order Type
               FROM afpo
               INTO TABLE t_afpo
               WHERE aufnr IN s_order
               AND   wemng IN s_dqt
               AND   matnr IN s_matnr
               AND   pwerk IN s_plant
               AND   dauat = c_ro.
        IF sy-subrc = 0.
          SORT t_afpo BY aufnr matnr pwerk.
    *C--FETCH THE OBJECT NUMBER
          SELECT aufnr "ORDER number
                 objnr "Object number
                 FROM aufk
                 INTO TABLE t_aufk
                 FOR ALL ENTRIES IN t_afpo
                 WHERE aufnr = t_afpo-aufnr.
          IF sy-subrc = 0.
            SORT t_aufk BY aufnr objnr.
    *C--FETCH THE Target Quantiity
            SELECT aufnr "ORDER number
                   gamng "Total order quantity target quantity
                   FROM afko
                   INTO TABLE t_afko
                   FOR ALL ENTRIES IN t_afpo
                   WHERE aufnr = t_afpo-aufnr
                   AND   gamng IN s_tqt.
            IF sy-subrc = 0.
              SORT t_afko BY aufnr .
            ENDIF.
          ENDIF.
        ELSE.
          MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
          LEAVE LIST-PROCESSING.
        ENDIF.
    *C--Begin of change DF 1232137- (Transport # :CIDK980530 )
      ENDIF.
      IF p_psd EQ c_x.
        SELECT aufnr "ORDER number
               wemng "Quantity of goods received for the order item
               matnr "MATERIAL NUMBER
               pwerk "PLANT
               dauat "Order Type
               FROM afpo
               INTO TABLE t_afpo
               WHERE aufnr IN s_order
               AND   wemng > 0
               AND   matnr IN s_matnr
               AND   pwerk IN s_plant
               AND   dauat = c_ro.
    if sy-subrc = 0.
    *C--FETCH THE OBJECT NUMBER
        IF  NOT t_afpo[] IS INITIAL.
          SORT t_afpo BY aufnr matnr pwerk.
          SELECT aufnr "ORDER number
                 objnr "Object number
                 FROM aufk
                 INTO TABLE t_aufk
                 FOR ALL ENTRIES IN t_afpo
                 WHERE aufnr = t_afpo-aufnr.
          IF sy-subrc = 0.
            SORT t_afko BY aufnr gamng.
          ELSE.
            MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
            LEAVE LIST-PROCESSING.
          ENDIF.
        ENDIF.
        IF NOT t_afpo[] IS INITIAL.
    *C--FETCH THE Target Quantiity
          SELECT aufnr "ORDER number
                 gamng "Total order quantity target quantity
                 FROM afko
                 INTO TABLE t_afko
                 FOR ALL ENTRIES IN t_afpo
                 WHERE aufnr = t_afpo-aufnr
                 AND   gamng <> t_afpo-wemng .
          IF sy-subrc = 0.
            SORT t_afko BY aufnr gamng.
          ELSE.
            MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
            LEAVE LIST-PROCESSING.
          ENDIF.
        ENDIF.
      ELSE.
        MESSAGE text-e03 TYPE c_s. " No data for the selection criteria
        LEAVE LIST-PROCESSING.
      ENDIF.
    Edited by: Thomas Zloch on Jan 5, 2011 1:30 PM please use code tags

    Hi friend,
    Try using MACRO and dynamic WHERE condition.
    Group simialr Select statements under a Macro.
    Build a dynamic where by checking conditions
    Call macro passing dynamic where condition.
    TABLES afpo.
    DATA: str TYPE string.
    *Macro definition
    DEFINE operation.
      select single *
           from afpo into afpo
           where (&1).    " Dynamic condition
    END-OF-DEFINITION.
    *Build dynamic WHERE by checking some conditions
    *If conditon 
    CONCATENATE 'AUFNR = ''000000700008''' 'AND POSNR = ''0001''' INTO str SEPARATED BY space.
    *Else
    CONCATENATE 'AUFNR = ''000000700008''' 'AND POSNR = ''0002''' INTO str SEPARATED BY space.
    *Endif.
    *Call Macro passing dynamic WHERE condition
    operation str.

  • Help! Inaccessible iterator when using dynamic query

    Hi!
    I have a problem retreiving results from a dynamic query into sqlj iterator.
    I consulted the Oracle App Dev Guide and Oracle SQLJ Dev Guide and wrote the following code:
    <PRE>
    package pmServer;
    #sql iterator LocIterator (int id, String name);
    public class pmRISDImpl
    public int GetLocations(...)
    LocIterator locIt;
    String q = "select ID, NAME from PMADM.LOCATIONS";
    #sql
    BEGIN
    open :OUT locIt for :q;
    END;
    </PRE>
    When I try to compile it using tools provided by JDeveloper ver 3.2.2.(Build 915) for JDK 1.2.2 I get error for #sql statement:
    Inaccessible Java type for host item locIt (at position #1): pmServer.LocIterator
    and warning:
    Type pmServer.LocIterator of host item locIt (at position #1) is not permitted in JDBC. This will not be portable.
    Althow the code is identcal to those demonstrated in Oracle document "Oracle8 i
    SQLJ Developers Guide and Reference
    Release 3 (8.1.7)
    July 2000
    Part No. A83723-01" pp 12-67 (PL/SQL in SQLJ for Dynamic SQLDynamicDemo.sqlj). There it looks like
    <PRE>
    private static void dynamicSelectMany(String what_cond)
    throws SQLException {
    System.out.println("dynamic multi-row query on table emp");
    Employees empIter;
    // table/column names cannot be bind args in dynamic PL/SQL, so
    // build up query as Java string
    String query = "select ename, sal from emp " +
    (((what_cond == null) &#0124; &#0124; (what_cond.equals(""))) ? "" :
    (" where " + what_cond)) +
    "order by ename";
    #sql {
    begin
    open :OUT empIter for -- opening ref cursor with dynamic query
    :query;
    -- can have USING clause here if needed
    end;
    while (empIter.next()) {
    System.out.println("Employee " + empIter.ename() +
    " has salary " + empIter.sal() );
    empIter.close();
    </PRE>
    Please guide me what should I do to get it working.
    null

    In the CAST statement the SQLJ runtime must be able to produce an instance of you SQLJ iterator using Java reflection.
    This necessitates that the iterator class must be accessible by public.
    You have two options:
    (1) Declare the iterator public. This requires that you put it in its own file LocIterator.sqlj:
    #sql public iterator LocIterator (int id, String name);
    (2) Declare the iterator as an inner class. In this case you want to make it public static (that is it does not require an instance of the outer class in scope). You might write the following.
    package pmServer;
    public class pmRISDImpl
    #sql public static iterator LocIterator (int id, String name);
    (3) If you are using Oracle 9i you have another option. You can embed dynamic SQL fragments directly in your SQLJ code and do not need to use the CAST:
    public int GetLocations(...)
    LocIterator locIt;
    String q = "PMADM.LOCATIONS";
    #sql locIt = { select ID, NAME from :{q} }; // Note new syntax :{q} for embedding SQL source code
    }

  • 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

Maybe you are looking for

  • Field Explorer help, not all Database Fields available

    Greetings all, I'm new to Crystal Reports (version XI by the way) and Tigerpaw.  I've had some great luck editing existing reports to the specifications we've needed thus far.  But now I've run into a real problem, it seems small, but it's important

  • Horizontal Menu Bar not formatting correctly in IE

    I am trying to get my menu bar to properly format in IE. It works fine in Opera, Firefox, and Safari. What I am having problems with is with how the sub menus pop up. In IE they show up above the menu bar instead of below the menu bar. Any help would

  • ALV In back ground

    Hi Friends,               I am running ALV list in background. Output is coming , but some of the columns are getting truncated in output. which mean it was not showing all the out put. i am having 16 columns, but it is showing only 12 fields in full

  • OC gtx 560ti to 1ghz

    hey i've been trying to OC my msi gtx 560ti in SLI to both at 1ghz but unable to do so I can only clock 970mhz @ the max voltage using msi afterburner and ppl is able to use the same card n get to 1ghz at a lower voltage hw do they do so???? here a v

  • Windows 2000 Error

    Hi all, I am receiving a error when running a projector on Windows 2000. "Unable to locate DLL. The dynamic link library gdiplus.dll could not be found.." I have authored the project on macintel, and downloaded and installed the latest mac hot fix fo