Build dynamic SQL query in Database Adapter.

Hi All,
I have a requirement to build dynamic sql query at Database Adapter.
My BPEL process is getting search spec as input from siebel. I need to process this searchspec in BPEL and need to build the SQL query dynamically at Database Adapter to fetch the records from DB.
it goes like this....
1. Sieble Search Spec: city1 OR city2 OR city3 OR city4 .....
I need to build query as
select * from S_ADDR_PER where city like 'city1' OR city like 'city2' OR city like 'city3' OR city like 'city4' ......
2. Siebel Search spec: city1 AND country1 AND state1....
I need to build query as
Select * from S_ADDR_PER where city like 'city1' AND country like 'country1' AND state like 'state1' ....
3. Siebel Search spec: state
I need to build query as
select * from S_ADDR_PER where state like '%state%';
Is it feasible in Database Adapter? if its Yes.
Any guidelines to achieve this?
Thank you
Chandra

Hi All,
I have a requirement to build dynamic sql query at Database Adapter.
My BPEL process is getting search spec as input from siebel. I need to process this searchspec in BPEL and need to build the SQL query dynamically at Database Adapter to fetch the records from DB.
it goes like this....
1. Sieble Search Spec: city1 OR city2 OR city3 OR city4 .....
I need to build query as
select * from S_ADDR_PER where city like 'city1' OR city like 'city2' OR city like 'city3' OR city like 'city4' ......
2. Siebel Search spec: city1 AND country1 AND state1....
I need to build query as
Select * from S_ADDR_PER where city like 'city1' AND country like 'country1' AND state like 'state1' ....
3. Siebel Search spec: state
I need to build query as
select * from S_ADDR_PER where state like '%state%';
Is it feasible in Database Adapter? if its Yes.
Any guidelines to achieve this?
Thank you
Chandra

Similar Messages

  • Dynamically Pass sql query in Database adapter

    hi',
    How can we dynamically pass sql query in Database adapter, is there any way, I am using SOA 11G.
    Thanks
    Yatan

    Hi,
    Tried that too. No luck. Gives me this.
    The selected operation process could not be invoked.
    An exception occured while invoking the webservice operation. Please see logs for more details.
    oracle.sysman.emSDK.webservices.wsdlapi.SoapTestException: Exception occured when binding was invoked.
    Exception occured during invocation of JCA binding: "JCA Binding execute of Reference operation 'selectUsingIn' failed due to: Pure SQL Exception.
    Pure SQL Execute of select interface_id, property_name, property_value from ( (?) ) failed.
    Caused by java.sql.SQLSyntaxErrorException: ORA-00903: invalid table name
    The invoked JCA adapter raised a resource exception.
    Please examine the above error message carefully to determine a resolution.
    Regards,
    Neeraj Sehgal

  • Build dynamic sql query

    We would like to build our sql statements based on the parameters passed in. Does anyone know how to do this.
    for example say something like
    select business_name from business where
    if input_user_id <> "" then
    user_id = input_user_id;
    else
    user_manager_id = input_manager_id;
    end if;

    Hi Howard
    Use a reference parameter in your query. Set the initial value of referece to "user_manager_id=input_manager_id". At runtime, the user may change the "WHERE" clause by entering an appropriate value in the parameter form.
    * Create a query as: select business_name from business where &P_1
    * The initial value of P_1 should be set to: user_manager_id=input_manager_id
    * At runtime, the user will be prompted to enter values for P_1. The user may then specify "user_id=input_user_id" for P_1 or leave it alone.
    Regards
    Sripathy

  • To build dynamic SQL Query using some conditions: Pseudo code required

    Hi,
    I have a requirement where in i have to build a dynamic query based on one count.
    Some details on requirement:
    1) It's a Proc where i need to return some columns
    2) There are some fix set of columns
    3) Based on one Count column, i have to decide the rest of the columns.
    Consider there is an employee who can work on 'N' number of assignments.
    For a particular employee i have to return all the predefined details of assignments like:
    1) Assignment Name
    2) Assignmanet Id
    3) Assignemnt Start Date
    4) Assignment End Date
    This 'N' can vary from employee to employee. Based on which i have to return my result set. For instance if employee has 3 assignemnts, i have to return Fix columns( employee info) + (3*4) columns. Similarly if the employee has 4 assignments, i will be returning Fix columns + (4*4) columns.
    Certainly, the Employee ID is coming as an I/P parameter.
    The source table is a vertical table having all details of the employee assignments.
    Can anyone help me in coding this proc with the help of some pseudo code?

    Do you mean you need something like this to be executed dynamically for some known n := max(count(assignment_id))
    NOT TESTED !
    select e.dept_id,e.emp_id,e.epm_name,
           substr(x1,1,instr(x1,';',1,1) - 1) assignment_name_1,
           to_number(substr(x1,instr(x1,';',1,1) + 1,instr(x1,';',1,2) - instr(x1,';',1,1) - 1))) assignment_id_1,
           to_date(substr(x1,instr(x1,';',1,1) + 1,instr(x1,';',1,3) - instr(x1,';',1,2) - 1)),'yyyymmdd') assignment_start_date_1,
           to_date(substr(x1,instr(x1,';',1,1) + 1,instr(x1,';',1,3) + 1)),'yyyymmdd') assignment_end_date_1,
           substr(x2,1,instr(x2,';',1,1) - 1) assignment_name_2,
           to_number(substr(x2,instr(x2,';',1,1) + 1,instr(x2,';',1,2) - instr(x2,';',1,1) - 1))) assignment_id_2,
           to_date(substr(x2,instr(x2,';',1,1) + 1,instr(x2,';',1,3) - instr(x2,';',1,2) - 1)),'yyyymmdd') assignment_start_date_2,
           to_date(substr(x2,instr(x2,';',1,1) + 1,instr(x2,';',1,3) + 1)),'yyyymmdd') assignment_end_date_2,
           substr(xn,1,instr(xn,';',1,1) - 1) assignment_name_n,
           to_number(substr(xn,instr(xn,';',1,1) + 1,instr(xn,';',1,2) - instr(xn,';',1,1) - 1))) assignment_id_n,
           to_date(substr(xn,instr(xn,';',1,1) + 1,instr(xn,';',1,3) - instr(xn,';',1,2) - 1)),'yyyymmdd') assignment_start_date_n,
           to_date(substr(xn,instr(xn,';',1,1) + 1,instr(xn,';',1,3) + 1)),'yyyymmdd') assignment_end_date_n
      from (select e.dept_id,e.emp_id,e.epm_name,
                   max(decode(rnk,1,x)) x1,
                   max(decode(rnk,1,x)) x2,
                   max(decode(rnk,1,x)) xn
              from (select e.dept_id,e.emp_id,e.epm_name,
                           a.assignment_name||';'||to_char(a.assignment_id)||';'||
                           to_char(a.assignment_start_date,'yyyymmdd')||';'||to_char(a.assignment_end_date,'yyyymmdd') x,
                           dense_rank() over (partition by e.dept_id,e.emp_id,e.epm_name order by a.assignment_id) rnk
                      from employees e,assignments a
                     where e.emp_id = a.emp_id
             group by e.dept_id,e.emp_id,e.epm_name
           )Regards
    Etbin

  • Build stored procedure from a dynamic SQL query

    I have the following method, that receives a string from a textbox and creates a dynamic select command. Since I am using a dataSet I cannot execute a dynamic SQL query by calling a method of a strongly-typed dataset (.xsd). I have been told that the best
    way to do this is to pass an array of values to the stored procedure.
    But I have no clue how to build the stored procedure.
    string[] allWords = txtSearch.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    string sql = "SELECT Books.ISBN, Books.Title, Books.Tag, Books.Image, Books.photoType, Publishers.Name AS publisherName FROM Books INNER JOIN Publishers ON Books.codPublisher = Publishers.codPublisher WHERE ";
    using (SqlCommand command = new SqlCommand())
    for (int i = 0; i < allWords.Length; ++i)
    if (i > 0)
    sql += "OR ";
    string paramName = "@param" + i.ToString();
    sql += string.Format("(Books.Title LIKE {0}) ", paramName);
    command.Parameters.AddWithValue(paramName, allWords[i] + "%");
    command.CommandText = sql;
    //execute the SQL query against the db...

    After hours around this, I have came with this solution.
    private SqlConnection sqlConn = new SqlConnection();
    private System.Data.DataSet dataSet = new System.Data.DataSet();
    private System.Data.DataTable dataTable;
    private System.Data.DataRow dataRow;
    private SqlCommand search(string searchParam, int searchOption)
    SqlCommand command = new SqlCommand();
    string sql;
    string[] allWords = searchParam.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    if (searchOption == 1)
    sql = "SELECT Livros.ISBN, Livros.Titulo, Livros.Tema, Livros.Resumo, Livros.Imagem, Livros.fotoTipo, Editoras.Nome AS nomeEditora FROM Livros INNER JOIN Editoras ON Livros.codEditora = Editoras.codEditora WHERE ";
    else
    sql = "SELECT Livros.ISBN, Livros.Titulo, Livros.Tema, Livros.Resumo, Livros.Imagem, Livros.fotoTipo, Editoras.Nome AS nomeEditora FROM Livros INNER JOIN livrosAutores ON Livros.ISBN = livrosAutores.ISBN INNER JOIN Autores ON livrosAutores.idAutor = Autores.idAutor INNER JOIN Editoras ON Livros.codEditora = Editoras.codEditora WHERE ";
    using (command)
    for (int i = 0; i < allWords.Length; ++i)
    if (i > 0)
    sql += "OR ";
    if (searchOption == 1)
    sql += string.Format("(Livros.Titulo LIKE '%{0}%') ", allWords[i]);
    else
    sql += string.Format("(Livros.Autor LIKE '%{0}%') ", allWords[i]);
    command.CommandText = sql;
    return command;
    protected void Bind()
    sqlConn.ConnectionString = Properties.Settings.Default.BibliotecaConnectionString;
    string connectionString = sqlConn.ConnectionString.ToString();
    SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(search(searchText, searchOption).CommandText, connectionString);
    sqlDataAdapter.Fill(dataSet, "livrosTitulo");
    dataTable = dataSet.Tables["livrosTitulo"];
    dataGrid.DataContext = dataTable.DefaultView;

  • Dynamic where clause in database adapter

    Hi
    I have requirement to develop SOA service for search page! The back-end query for search is required to have where clauses to be appended to SELECT statement dynamically depending upon search criteria the user selects!
    E.g. if user is searching employee from a portal! If employee selects mobile number of the employee, or joining date range or other criteria, then accordingly appropriate clauses are to be appended to SEARCH SELECT statement.
    Can we achieve same while implementing executing database query through database adapter from BPEL service?
    Thanks In Advance
    Priyadarshi 

    It is difficult using the standard database adapter approach. You may have to use nested sql queries.Following is a good example of the same.
    Neeraj Sehgal - Experimenting with SOA: Pass multiple parameters, dynamic query in Pure SQL in Database Adapter
    If your only problem in using this that you are hard coding the connection details  , you can use the datasource jndi name in the query. hence you will not be required to change your code when moving from one env to other env. You just have to take care of keeping the jndi name same in all the env.

  • Best way to spool DYNAMIC SQL query to file from PL/SQL

    Best way to spool DYNAMIC SQL query to file from PL/SQL [Package], not SqlPlus
    I'm looking for suggestions on how to create an output file (fixed width and comma delimited) from a SELECT that is dynamically built. Basically, I've got some tables that are used to define the SELECT and to describe the output format. For instance, one table has the SELECT while another is used to defined the column "formats" (e.g., Column Order, Justification, FormatMask, Default value, min length, ...). The user has an app that they can use to customize the output...which leaving the gathering of the data untouched. I'm trying to keep this formatting and/or default logic out of the actual query. This lead me into a problem.
    Example query :
    SELECT CONTRACT_ID,PV_ID,START_DATE
    FROM CONTRACT
    WHERE CONTRACT_ID = <<value>>Customization Table:
    CONTRACT_ID : 2,Numeric,Right
    PV_ID : 1,Numeric,Mask(0000)
    START_DATE : 3,Date,Mask(mm/dd/yyyy)The first value is the kicker (ColumnOrder) as well as the fact that the number of columns is dynamic. Technically, if I could use SqlPlus...then I could just use SPOOL. However, I'm not.
    So basically, I'm trying to build a generic routine that can take a SQL string execute the SELECT and map the output using data from another table to a file.
    Any suggestions?
    Thanks,
    Jason

    You could build the select statement within PL/SQL and open it using a cursor variable. You could write it to a file using the package 'UTL_FILE'. If you want to display the output using SQL*Plus, you could have an out parameter as a ref cursor.

  • A challenging dynamic SQL query problem

    hi All,
    I have a very interesting problem at work:
    We have this particular table defined as follows :
    CREATE TABLE sales_data (
    sales_id NUMBER,
    sales_m01 NUMBER,
    sales_m02 NUMBER,
    sales_m03 NUMBER,
    sales_m04 NUMBER,
    sales_m05 NUMBER,
    sales_m06 NUMBER,
    sales_m07 NUMBER,
    sales_m08 NUMBER,
    sales_m09 NUMBER,
    sales_m10 NUMBER,
    sales_m11 NUMBER,
    sales_m12 NUMBER,
    sales_prior_yr NUMBER );
    The columns 'sales_m01 ..... sales_m12' represents aggregated monthly sales, in which 'sales_m01' translates to 'sales for the month of january, january being the first month, 'sales_m02' sales for the month of february, and so on.
    The problem I face is that we have a project which requires that a parameter be passed to a stored procedure which stands for the month number which is then used to build a SQL query with the following required field aggregations, which depends on the parameter passed :
    Sample 1 : parameter input: 4
    Dynamically-built SQL query should be :
    SELECT
    SUM(sales_m04) as CURRENT_SALES,
    SUM(sales_m01+sales_m02+sales_m03+sales_m04) SALES_YTD
    FROM
    sales_data
    WHERE
    sales_id = '0599768';
    Sample 2 : parameter input: 8
    Dynamically-built SQL query should be :
    SELECT
    SUM(sales_m08) as CURRENT_SALES,
    SUM(sales_m01+sales_m02+sales_m03+sales_m04+
    sales_m05+sales_m06+sales_m07+sales_m08) SALES_YTD
    FROM
    sales_data
    WHERE
    sales_id = '0599768';
    So in a sense, the contents of SUM(sales_m01 ....n) would vary depending on the parameter passed, which should be a number between 1 .. 12 which corresponds to a month, which in turn corresponds to an actual field range on the table itself. The resulting dynamic query should only aggregate those columns/fields in the table which falls within the range given by the input parameter and disregards all the remaining columns/fields.
    Any solution is greatly appreciated.
    Thanks.

    Hi another simpler approach is using decode
    try like this
    SQL> CREATE TABLE sales_data (
      2  sales_id NUMBER,
      3  sales_m01 NUMBER,
      4  sales_m02 NUMBER,
      5  sales_m03 NUMBER,
      6  sales_m04 NUMBER,
      7  sales_m05 NUMBER,
      8  sales_m06 NUMBER,
      9  sales_m07 NUMBER,
    10  sales_m08 NUMBER,
    11  sales_m09 NUMBER,
    12  sales_m10 NUMBER,
    13  sales_m11 NUMBER,
    14  sales_m12 NUMBER,
    15  sales_prior_yr NUMBER );
    Table created.
    SQL> select * from sales_data;
      SALES_ID  SALES_M01  SALES_M02  SALES_M03  SALES_M04  SALES_M05  SALES_M06  SALES_M07  SALES_M08  SALES_M09  SALES_M10  SALES_M11  SALES_M12 SALES_PRIOR_YR
             1        124        123        145        146        124        126        178        189        456        235        234        789          19878
             2        124        123        145        146        124        126        178        189        456        235        234        789          19878
             1        100        200        300        400        500        150        250        350        450        550        600        700          10000
             1        101        201        301        401        501        151        251        351        451        551        601        701          10000----now for your requirement. see below query if there is some problem then tell.
    SQL> SELECT sum(sales_m&input_data), DECODE (&input_data,
      2                 1, SUM (sales_m01),
      3                 2, SUM (sales_m01 + sales_m02),
      4                 3, SUM (sales_m01 + sales_m02 + sales_m03),
      5                 4, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04),
      6                 5, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04 + sales_m05),
      7                 6, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06),
      8                 7, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07),
      9                 8, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08),
    10                 9, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09),
    11                 10,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10),
    12                 11,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10+sales_m11),
    13                 12,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10+sales_m11+sales_m12)
    14                ) total
    15    FROM sales_data
    16   WHERE sales_id = 1;
    Enter value for input_data: 08
    Enter value for input_data: 08
    old   1: SELECT sum(sales_m&input_data), DECODE (&input_data,
    new   1: SELECT sum(sales_m08), DECODE (08,
    SUM(SALES_M08)      TOTAL
               890       5663

  • Flash chart with dynamic sql query does not display

    Hi,
    In my schema SIVOA I have a lot of tables declared like this :
      CREATE TABLE "SIVOA"."EVV_xxxx"
       (     "CLEF_VAR" NUMBER(4,0),
         "DATE1" DATE,
         "VALEUR" NUMBER(16,8) Only the last part of the name changes "xxxx". For example E009, E019, etc....
    I am making a chart page with report and want the user to select a name of a table and I will display using dynamic sql query, the table report and chart.
    P184_ENAME is a select list returning the last part of the name of the table, fro example 'E009', 'E019', etc.
    P8_CLEF_VAR is an item containing a value. This value is a key retrieved like this :SELECT CLEF_VAR
    FROM SIVOA.SITE_ECHELLE
    WHERE SITE = :P184_ENAMEI built a classic report using a sql dynamic function :DECLARE
    x VARCHAR2 (4000);
    BEGIN
    x := 'SELECT NULL, DATE1, VALEUR FROM SIVOA.EVV_'
    || UPPER(:p184_ename)
    || ' WHERE CLEF_VAR = :p8_clef_var' ;
    RETURN (x);
    END;:p8_clef_var is an itme containing the value '4544'.
    This works perfectly fine !
    When I use this sql fucytion into a flash chart it does not work. I get this message "No data found".
    I do not understand why a the report get a result and not the chart !
    But if i hard-code the number of the CLEF_VAR instead of fetching it from :p8_clef_var I get a nice chart ! Go figure !DECLARE
    x VARCHAR2 (4000);
    BEGIN
    x := 'SELECT NULL, DATE1, VALEUR FROM SIVOA.EVV_'
    || UPPER(:p184_ename)
    || ' WHERE CLEF_VAR = 4544 ' ;
    RETURN (x);
    I cannot stay with the key (CLEF_VAR) hard-coded unformtunately !
    My question is how to get the chart displaying properly ??
    Thank you for your kind answers.
    Christian                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Alex,
    Using your request, with the classic report I get results (data), but I get the same message with the Flash chart : "No data found" ! I don't know how to investigate this. i tried many things but nothing works.
    Christian
    PS I tried this :
    DECLARE
       X   VARCHAR2 (4000);
    BEGIN
    x := 'SELECT NULL, DATE1, ROUND(VALEUR,2) FROM SIVOA.EVV_'
          || UPPER (:p184_ename) ||
          ' WHERE CLEF_VAR = '
          || :p8_clef_var ||
          ' AND DATE1 BETWEEN TO_DATE ('''
    ||:P8_DATE_DEBUT||''', ''DD/MM/YYYY HH24:MI'') AND TO_DATE ('''
    ||:P8_DATE_FIN||''', ''DD/MM/YYYY HH24:MI'')'
    RETURN (X);
    END; But it does not work either. I could find that the SLQ syntax generated is good becaus I put it into an item which display the return done by the pls/sql.
    What is sttange also with the classic report is that if I do click on next or previous to see another rows, I get the message "No data found". If I try to export the report I get an excel file with "No data fouid".
    Does anybody already tried my "need" here ? i find strange thant I should not be the firs one trying to get a report an tables which name would be "dynamic".
    Tahnk you.
    Edited by: Christian from France on Feb 13, 2009 3:05 AM

  • SSRS - Stored procedure with Dynamic SQL Query

    Am calling stored procedure in SSRS report.  I have used Dynamic SQL query in stored procedure as I don't know the column name and column count.  And I have used like below at end of the stored procedure "select * from ##temptable".
    As I have used dynamic column, am not able to create report with this stored procedure.  Can someone help me out to resolve this issue.
    It will be highly appreciated if I get help. 
    Thanks

    I have tried everything.  But nothing has worked out. 
    If I get solution for below issue, it would be highly appreciated.
    "An error occurred during local report processing.
    The definition of the repport 'Main Report' is invalid.
    The report defintion is not valid.  Details: The report definition has an invalid target namespace 'http://schemas.microsoft.com/sqlserver/reporting/2010/01/reportdefinition' which cannot be upgraded.
    Thanks
    Hello,
    I would suggest you post the complete error message to us for further investigation, if you preview the report before you deploy you may get a more detailed error that will help diagnose the source of the problem.
    This issue is more related to SQL Server Reporting Services, it's more appropriate to discuss it in the forum below:
    https://social.technet.microsoft.com/Forums/sqlserver/en-US/home?forum=sqlreportingservices
    Don't forget to elaborate your issue with more detail.
    For the manual column, it might be the calculated field in SSRS. Here is the article for your reference, please see:
    http://technet.microsoft.com/en-us/library/dd239322(v=sql.110).aspx
    Regards,
    Elvis Long
    TechNet Community Support

  • How Can I find SQL Query in Database

    Dear Experts,
    How Can I find SQL Query in Database.

    Hi,
    U mena what query got executed in db? u can try V$SQL for it.
    Regards
    Bharath

  • How to notify in case SQL query(JDBC sender adapter) does not fetch records

    hi,
    How can we notify(by alerts or something) in case SQL query(JDBC sender adapter) does not fetch records? In channels logs it only says processing started & finished(no message is created for same).
    Thanks,
    Mayank

    Hi,
    1 ) What is exact audit log message ?
    2) Try fetching the count in SQL statement  if there are any valid records it will give the count.
        May for testing you can use <TEST> in update statement.
    3) Have you used taskTimeout parameter ?
    4) Are multiple channels polling on same table ?
    regards
    Ganga

  • Proxy to JDBC scenario need dynamic sql query for sender .

    Hi Experts,
    I am developing proxy to jdbc scenario. in this i need to pass dynamic sql query  whre we are passing classical method like below.
    while we are passing select stmt in constant and mapped with access field  and key field mapped with key field.
    MY requirement is like instead of passing select stmt in constant where i can generate dynamically and passed in one field and mapped with access field.

    Hi Ravinder,
    A simple UDF or use of graphical mapping functions in most cases should provide you everything you need to construct a dynamic SQL statement for your requirement.
    Regards,
    Ryan Crosby

  • Need generic dynamic sql query to generate nodes depending on dealer levels

    Input table:
    create table #test(dealerid integer ,dealerlvl integer)
    insert into #test values(1,1)
    insert into #test values(1,2)
    insert into #test values(1,3)
    insert into #test values(1,4)
    insert into #test values(2,1)
    insert into #test values(2,2)
    insert into #test values(2,3)
    insert into #test values(2,4)
    insert into #test values(2,5)
    insert into #test values(2,6)
    go
    create table #test2(dealerid integer,node integer,prntnode integer,dealerlvl integer)
    insert into #test2 values (1,234,124,2)
    insert into #test2 values (1,123,234,1)
    insert into #test2 values (1,238,123,2)
    insert into #test2 values (1,235,238,3)
    insert into #test2 values (1,253,235,4)
    insert into #test2 values (2,21674,124,3)
    insert into #test2 values (2,1233,21674,1)
    insert into #test2 values (2,2144,1233,2)
    insert into #test2 values (2,2354,2144,3)
    insert into #test2 values (2,24353,2354,4)
    insert into #test2 values (2,245213,24353,5)
    insert into #test2 values (2,2213,245213,6)
    Expected result :
    I have two test case here with dealerID1 and dealerID 2 
    Result for DealerID1
    Result needed for DealerID2:
    the levels for dealers might change (Dealer1 has 4 levels, and Dealer 2 has 6 levels) so i need to create an dynamic sql query which lists each node as separate columns depending on the levels. 
    I have hacked the query to give the result I need 
    select a.dealerid,a.node as Lvl1,b.node as lvl2,c.node as lvl3,d.node as lvl4
    from #test2 a 
    join #test2 b on a.node=b.prntnode
    join #test2 c on b.node=c.prntnode
    join #test2 d on c.node=d.prntnode
    where a.dealerid=1 and a.dealerlvl=2
    select  a.dealerid,a.node asLvl1,
    b.node as lvl2,c.node as lvl3,d.node as lvl4,e.node as lvl5,f.node as lvl6--,a.dealerlvl,a.dealerid
    from #test2 a 
    join #test2 b on a.node=b.prntnode
    join #test2 c on b.node=c.prntnode
    join #test2 d on c.node=d.prntnode
    join #test2 e on d.node=e.prntnode
    join #test2 f on e.node=f.prntnode
    where a.dealerid=2 and a.dealerlvl=3
    I am sure there is a better way to do this with dynamic sql. please help.
    Thanks

    -- Dynamic PIVOT
     DECLARE @T AS TABLE(y INT NOT NULL PRIMARY KEY);
    DECLARE
       @cols AS NVARCHAR(MAX),
       @y    AS INT,
       @sql  AS NVARCHAR(MAX);
    -- Construct the column list for the IN clause
     SET @cols = STUFF(
       (SELECT N',' + QUOTENAME(y) AS [text()]
        FROM (SELECT DISTINCT dealerlvl AS y FROM dbo.test2) AS Y
        ORDER BY y
        FOR XML PATH('')),
       1, 1, N'');
    -- Construct the full T-SQL statement
     -- and execute dynamically
     SET @sql = N'SELECT *
     FROM (SELECT dealerid, dealerlvl, node
           FROM dbo.Test2) AS D
       PIVOT(MAX(node) FOR dealerlvl IN(' + @cols + N')) AS P;';
    EXEC sp_executesql @sql;
     GO

  • Creating a dynamic SQL query builder class

    I have a jobs table where each row contains information about jobs run on a machine. I have a web view of this database which shows different information and queries for this information are built using the following fields:
    TYPE
    TITLE
    NODE
    STATUS (an array of 4 different possible statuses)
    TIMESTAMP
    GUID (will be used when a view of a specific job (row in the table) is requested, no other search criteria needed when this view is required.)
    All the criteria will be passed from the view layer into a search criteria object which is then passed to the DAO class which passes it to a BuildSQL class to use it to build the SQL.
    There are many different "views" of the data which will result in many different combinations of criteria being passed down to the data access layer. (for example a status of failed and a timestamp resulting in all the jobs run in the last 2 hours)
    As there are a number of different search criteria used in each query I'm having trouble designing the class to dynamically build the query. Are there any standard ways of doing this out there that could guide me?
    At the moment I'm seeing this class as being a large combination of if statements and not really being very dynamic.
    I was thinking maybe checking all the criteria to see if its null, if so ignore it straight away and then running through all the other criteria and appending one by one to the may SELECT which has already been created. Quite how i'd decided whether it would need an AND or OR before it I dont know.
    Are there any standard proven ways to approach this because i've done a search here and on google and not really come back with much, so any advice would be great. I've got to say I'm pretty new to java and don't really have many bright ideas here!

    Well my dear friend... I did something special for a business logic support to an web autocomplete component.
    The criteria building was based on a custom variable into the SQL statement:
    SELECT * FROM TABLE WHERE __MC__ AND (FIXED CRITERIA)
    Where:
    *FIXED CRITERIA: Is a fixed criteria that doesn't variate
    *__MC__: Is a "custom variable" defined for me to make the replacement.
    There are two main clases:
    *SQLBuilder: It has many logic to build SQL Statements
    *Multicriteria: It has the specific logic to insert into a SQL statement multiple criterias
    // The SQLBuilder class
    public class SQLBuilder {
        public static final String MC = "__MC__";
        static String buildMultiCriteria(String sql, Object[] params) throws Exception {
            for(int i=0; i<params.length; i++) {
                if(params[i] instanceof MultiCriteria) {
                    sql = sql.replaceFirst("__MC__",
                            ((MultiCriteria)params).getCriteria());
    params[i] = null;
    return sql;
    // The MultiCriteria class
    public class MultiCriteria {
    public static final int BEGINS = 0;
    public static final int ENDS = 1;
    public static final int CONTAINS = 2;
    private String criteria = null;
    public MultiCriteria(String[] fields, String value, int type) throws Exception {
    String[] tokens = value.split(" ");
    StringBuffer sb = new StringBuffer("(");
    for(int i=0; i<fields.length; i++) {
    for(int j=0; j<tokens.length; j++) {
    if(tokens[j].length()>0) {
         sb.append(fields[i].toUpperCase());
         sb.append(" LIKE '");
         sb.append(toType(tokens[j], type));
         sb.append("'");
         if(j<tokens.length-1) sb.append(" OR ");
    if(i<fields.length-1) sb.append(" OR ");
    sb.append(")");
    criteria = sb.toString();
    public String getCriteria() {
    return criteria;
    private final String toType(String value, int type) throws Exception {
    switch(type) {
         case BEGINS:
         value = value + "%";
         break;
         case ENDS:
         value = "%" + value;      
         break;
         case CONTAINS:
         value = "%" + value + "%";      
         break;
         default:
         throw new Exception("Undefined MutiCriteria type");
    return value;
    // I use the MultiCriteria this way
    // criteria is a string introduced in a html input text
    // The class splits the string by " " and ensemble multiple criterias
    // for the given fields permuting them with the tokens resulting of the
    // split
    MultiCriteria mc = new MultiCriteria(
    new String[] {"FIELD_01", "FIELD_02"},
         criteria,
         MultiCriteria.CONTAINS
    I think this idea could help you.
    Anything else, write me at [email protected]
    Best Regards,

Maybe you are looking for

  • External NTSC Monitor - 4:3 and 16:9 Question

    I'm trying to find a configuration setting in FCP 5.0 when outputting to an external NTSC monitor that will force the image to "letterbox", rather than crop to 4:3. I have a nice Sony NTSC monitor, but it's not the model that allows switching between

  • Getting GL account error during goods receipt

    Hi Experts Have done configurational settings for CIN, later while doing goods receipt, getting error message: The GL account 11 doesnot exist in Chart of Account CAIN. Regards Ajay

  • [SOLVED] SQLDeveloper 2.1.x crash on launch (Mac OS 10.6)

    [EDIT] SOLVED: I was using the app "The Unarchiver" to unarchive the .tar.gz file, which corrupted the .app file. Instead, untar'ing the file on the command line using the tar binary worked: tar -zxvf sqldeveloper.tar.gz See here for other post that

  • Calendar quit unexpectedly

    Hi, I've upgraded to OS X Mavericks on family iMac. When I try to open calendar in one account (others are just fine), it keeps quitting unexpectedly. Do you have any idea why and how to fix it? Here is the log: Process:         Calendar [2603] Path:

  • Download file link in adf command link action

    Hi, i want to make a link on my web page , when my users click that link they can download a file how can i do that i use the thread Re: Download File Link in jspx but not works for me could any one help me to sort out the issue Thanks in advance