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

Similar Messages

  • Need a dynamic sql query

    how should I write the below query in dynamic query
    select
    case
    when answer_date = to_date('10/16/2209','MM/DD/YYYY') THEN to_date('10/16/2009','MM/DD/YYYY')
    ELSE answer_date
    end as ANSWER_DATE
    FROM
    answers_test ;
    OR
    select
    decode ( answer_date, to_date('10/16/2209','MM/DD/YYYY') ,to_date('10/16/2009','MM/DD/YYYY'), answer_date)
    FROM
    answers_test ;
    Thank you.
    Edited by: 839989 on Feb 25, 2011 9:03 PM

    both r equally well, but when dealing a equi operator i prefer decode.

  • 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

  • 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

  • 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

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

  • SQL query to generate Nested XML

    Hello,
    I use Oracle 11g R2 SOE....
    I have two main tables
    COMMERCIALS_PROPERTIES (com_id number PK , com_size number, project_id number, com_type number)
    COM_PHOTOS (ID number PK , com_id number FK, content blob, mimetype varchar2)
    Please, note the following has nothing to do with my problem:
    CONTENT and MIMETYPE columns. Also, the lookup tables: PROJECTS , COM_TYPE
    In APEX ( Application Express ) we can expose a report as RESTful web service in XML format:
    I am using this query to generate the XML 1 feed, but I need to tweak the query to generate XML 2 feed.
    Is it possible, how to do it ???
    Select
    "COM"."COM_ID" as "COM_ID",
    "COM"."COM_SIZE" as "SIZE",
    "PROJECTS"."PROJECT_NAME_EN" as "PROJECT",
    "COM_TYPES"."COM_TYPE" as "COM_TYPE",
    'http://fam-erp.com/apex/erp/fateh/'||IMG.ID as "ImgURL"
    FROM
    COM_PHOTOS IMG inner join COMMERCIALS_PROPERTIES "COM"
    on   IMG.COM_ID = COM.COM_ID
    inner join "PROJECTS" "PROJECTS"
    on "PROJECTS"."PROJECT_ID"="COM"."PROJECT_ID"
    inner join "COM_TYPE_LOOKUP" "COM_TYPES"
    on "COM_TYPES"."TYPE_ID"="COM"."COM_TYPE"
    WHERE
      COM.COM_ID < 80 order by 1h1. XML 1
    h2. Please look only at <COM_ID> and <ImgURL>
    <ROWSET>
    <ROW>
    <COM_ID>77</COM_ID>
    <SIZE>842</SIZE>
    <PROJECT>Bayswater Tower</PROJECT>
    <COM_TYPE>Office</COM_TYPE>
    <ImgURL>http://fam-erp.com/apex/erp/fateh/1410</ImgURL>
    </ROW>
    <ROW>
    <COM_ID>77</COM_ID>
    <SIZE>842</SIZE>
    <PROJECT>Bayswater Tower</PROJECT>
    <COM_TYPE>Office</COM_TYPE>
    <ImgURL>http://fam-erp.com/apex/erp/fateh/1412</ImgURL>
    </ROW>
    <ROW>
    <COM_ID>78</COM_ID>
    <SIZE>756</SIZE>
    <PROJECT>Bayswater Tower</PROJECT>
    <COM_TYPE>Office</COM_TYPE>
    <ImgURL>http://fam-erp.com/apex/erp/fateh/1425</ImgURL>
    </ROW>
    <ROW>
    <COM_ID>78</COM_ID>
    <SIZE>756</SIZE>
    <PROJECT>Bayswater Tower</PROJECT>
    <COM_TYPE>Office</COM_TYPE>
    <ImgURL>http://fam-erp.com/apex/erp/fateh/1429</ImgURL>
    </ROW>
    </ROWSET>---------------------------
    h1. XML 2
    h2. Please look only at <COM_ID> and <Images> and <ImgURL>
    <ROWSET>
    <ROW>
    <COM_ID>77</COM_ID>
    <SIZE>842</SIZE>
    <PROJECT>Bayswater Tower</PROJECT>
    <COM_TYPE>Office</COM_TYPE>
    <Images>
          <ImgURL>http://fam-erp.com/apex/erp/fateh/1410</ImgURL>
          <ImgURL>http://fam-erp.com/apex/erp/fateh/1412</ImgURL>
    </Images>
    </ROW>
    <ROW>
    <COM_ID>78</COM_ID>
    <SIZE>756</SIZE>
    <PROJECT>Bayswater Tower</PROJECT>
    <COM_TYPE>Office</COM_TYPE>
    <Images>
            <ImgURL>http://fam-erp.com/apex/erp/fateh/1425</ImgURL>
            <ImgURL>http://fam-erp.com/apex/erp/fateh/1429</ImgURL>
    </Images>
    </ROW>
    </ROWSET>

    Hi, Fateh
    One possible way is to use XML functions to create your XML.
    Using XML functions you can do the IMAGES as an XMLAGG subquery rather than join to the image table.
    Here's an example using SCOTT schema:
    SQL> select xmlelement(
      2            "ROWSET"
      3          , xmlagg(
      4               xmlelement(
      5                  "ROW"
      6                , xmlforest(
      7                     d.deptno as "ID"
      8                   , d.dname as "NAME"
      9                   , (
    10                        select xmlagg(
    11                                  xmlelement(
    12                                     "ImgUrl"
    13                                   , 'http://the.server.com/'||e.empno
    14                                  )
    15                                  order by e.empno
    16                               )
    17                          from scott.emp e
    18                         where e.deptno = d.deptno
    19                     ) as "Images"
    20                  )
    21               )
    22               order by d.deptno
    23            )
    24         ) the_xml
    25    from scott.dept d
    26    /* joins to the other tables EXCEPT image table */
    27  /
    THE_XML
    <ROWSET><ROW><ID>10</ID><NAME>ACCOUNTING</NAME><Images><ImgUrl>http://the.serverThat output is an XMLTYPE column (think of it as a CLOB with added functionality ;-) )
    My SQL*PLUS cuts the output, but believe me, it is all there.
    Just to show it, here's the same example wrapped in an XMLSERIALIZE function to pretty-print the XML:
    SQL> select xmlserialize(
      2            content
      3            xmlelement(
      4               "ROWSET"
      5             , xmlagg(
      6                  xmlelement(
      7                     "ROW"
      8                   , xmlforest(
      9                        d.deptno as "ID"
    10                      , d.dname as "NAME"
    11                      , (
    12                           select xmlagg(
    13                                     xmlelement(
    14                                        "ImgUrl"
    15                                      , 'http://the.server.com/'||e.empno
    16                                     )
    17                                     order by e.empno
    18                                  )
    19                             from scott.emp e
    20                            where e.deptno = d.deptno
    21                        ) as "Images"
    22                     )
    23                  )
    24                  order by d.deptno
    25               )
    26            )
    27            as varchar2(4000)
    28            indent size=2
    29         ) the_xml
    30    from scott.dept d
    31    /* joins to the other tables EXCEPT image table */
    32  /
    THE_XML
    <ROWSET>
      <ROW>
        <ID>10</ID>
        <NAME>ACCOUNTING</NAME>
        <Images>
          <ImgUrl>http://the.server.com/7782</ImgUrl>
          <ImgUrl>http://the.server.com/7839</ImgUrl>
          <ImgUrl>http://the.server.com/7934</ImgUrl>
        </Images>
      </ROW>
      <ROW>
        <ID>20</ID>
        <NAME>RESEARCH</NAME>
        <Images>
          <ImgUrl>http://the.server.com/7369</ImgUrl>
          <ImgUrl>http://the.server.com/7566</ImgUrl>
          <ImgUrl>http://the.server.com/7788</ImgUrl>
          <ImgUrl>http://the.server.com/7876</ImgUrl>
          <ImgUrl>http://the.server.com/7902</ImgUrl>
        </Images>
      </ROW>
      <ROW>
        <ID>30</ID>
        <NAME>SALES</NAME>
        <Images>
          <ImgUrl>http://the.server.com/7499</ImgUrl>
          <ImgUrl>http://the.server.com/7521</ImgUrl>
          <ImgUrl>http://the.server.com/7654</ImgUrl>
          <ImgUrl>http://the.server.com/7698</ImgUrl>
          <ImgUrl>http://the.server.com/7844</ImgUrl>
          <ImgUrl>http://the.server.com/7900</ImgUrl>
        </Images>
      </ROW>
      <ROW>
        <ID>40</ID>
        <NAME>OPERATIONS</NAME>
      </ROW>
    </ROWSET>For a webservice you do not need to pretty-print the XML that is returned by the webservice.
    I do not know APEX, so I do not know if APEX supports exposing an allready built piece of XML rather than exposing a query result.
    But my guess is that it should do it very nicely if you query an XMLTYPE datatype (that is - use the first of my examples rather than the pretty-printed one.)
    If you can't get APEX to do it this way, then I suggest you try asking in the APEX forum rather than the SQL forum ;-)

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • Need Oracle Payroll SQL Query

    Hello,
    I need Oracle Payroll SQL Query with result:
    First_name, Last_name, Payment_amount, Pay_date, Payroll_Frequency, Employement_status
    Any Help would be greatful appreciated

    You will need the following tales.
    per_all_people_f, per_all_assignments_f,pay_run_results,pay_run_result_values
    Query would e something like :
    select papf.first_name,
             papf.last_name,
             prrv.*
    From  apps.per_all_people_f papf
             apps.per_all_assignments_f paaf
             apps.pay_run_results prr,
             apps.pay_run_result_values prrv
    Where papf.person_id = paaf.person_id
    and papf.business_group_id = paaf.business_group_id
    and papf.current_employee_flag = 'Y'
    and paaf.primary_flag ='Y'
    and paaf.assignment_type = 'E'
    and trunc(sysdate) between papf.effective_start_date and papf.effective_end_date
    and trunc(sysdate) between paaf.effective_start_date and paaf.effective_end_date 
    and prr.assignment_id = paaf.assignment_id

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

  • 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

  • Trying to build a generic dynamic sql block

    Hi,
    I have this requirement of wanting to compare column values in source and target( which are almost of the same structure) based on what table name is input by the user.
    I came across a sql select statement developed by Tom kyte which kind of answers the question but what i am looking for is a more generic approach so that I can dynamically build a similar query and output very similar results.
    Tom's example
    So, using my assumptions and making your 'test case' (it isn't a test case yet, it is lacking) a better one:
    ops$tkyte%ORA10GR2> create table t1(c1 number(2) primary key, c2 varchar2(10), c3
    varchar2(10));
    Table created.
    ops$tkyte%ORA10GR2> create table t2(c1 number(2) primary key, c2 varchar2(10), c3
    varchar2(10));
    Table created.
    ops$tkyte%ORA10GR2>
    ops$tkyte%ORA10GR2> insert into t1 values(1,'a','c');
    1 row created.
    ops$tkyte%ORA10GR2> insert into t2 values(1,'b','c');
    1 row created.
    ops$tkyte%ORA10GR2>
    ops$tkyte%ORA10GR2> insert into t1 values(2,'a','b');
    1 row created.
    ops$tkyte%ORA10GR2> insert into t2 values(2,'a','c');
    1 row created.
    ops$tkyte%ORA10GR2>
    ops$tkyte%ORA10GR2> insert into t1 values(3,'a','b');
    1 row created.
    ops$tkyte%ORA10GR2> insert into t2 values(3,'a','b');
    1 row created.
    ops$tkyte%ORA10GR2>
    ops$tkyte%ORA10GR2> insert into t1 values(4,'a','b');
    1 row created.
    ops$tkyte%ORA10GR2> insert into t2 values(4,'x','y');
    1 row created.
    ops$tkyte%ORA10GR2>
    ops$tkyte%ORA10GR2> insert into t1 values(5,'a','b');
    1 row created.
    ops$tkyte%ORA10GR2>
    ops$tkyte%ORA10GR2> insert into t2 values(6,'a','b');
    1 row created.
    ops$tkyte%ORA10GR2>
    ops$tkyte%ORA10GR2>
    select case sum(new_cnt - old_cnt) over(partition by c1)
    when 1 then 'T2 (missing in T1)'
    when -1 then 'T1 (missing in T2)'
    else case old_cnt when 1 then 'T1' else 'T2' end
    end "TABLE"
    , C1 PK, C2, C3
    , case when new_cnt = 1 and count(*) over(partition by c1) > 1 then (
    case when lag(c2) over(partition by c1 order by new_cnt) = c2 then 0 else 1 end
    + case when lag(c3) over(partition by c1 order by new_cnt) = c3 then 0 else 2 end
    ) end COL_DIF_ID
    from (
    select c1, c2, c3, sum(old_cnt) old_cnt, sum(new_cnt) new_cnt from (
    select o.*, 1 old_cnt, 0 new_cnt from t1 o
    union all
    select n.*, 0 old_cnt, 1 new_cnt from t2 n
    ) group by c1, c2, c3 having sum(old_cnt) <> sum(new_cnt)
    ) order by c1, new_cnt
    TABLE PK C2 C3 COL_DIF_ID
    T1 1 a c
    T2 1 b c 1
    T1 2 a b
    T2 2 a c 2
    T1 4 a b
    T2 4 x y 3
    T1 (missing in T2) 5 a b
    T2 (missing in T1) 6 a b
    It beautifully does the job but can we make this more generic in any manner using dynamic sql ?

    Hi,
    try this:
    declare
    cTable1 varchar2(30):='T1';
    cTable2 varchar2(30):='T2';
    cPK varchar2(30):='c1';
    cSQL varchar2(4000):=null;
    bFirst boolean:=true;
    begin
    cSQL:='select t1.*,t2.*,(case when t1.'||cPK||' is null then ''Missing in T1'' else null end) exists_t1,(case when t2.'||cPK||' is null then ''Missing in T2'' else null end) exists_t2,';
    for c in(select column_name from
    (select column_name from  user_tab_columns where table_name=cTable1 and column_name!=cPK
    intersect
    select column_name from  user_tab_columns where table_name=cTable2 and column_name!=cPK)) loop
    if bFirst then
    cSQL:=cSQL||'(case when';
    bFirst:=false;
    else
    cSQL:=cSQL||' and ';
    end if;
    cSQL:=cSQL||'(t1.'||c.column_name||'=t2.'||c.column_name||' or (t1.'||c.column_name||' is null and t2.'||c.column_name||' is null))';
    end loop;
    cSQL:=cSQL||' then ''='' else ''!='' end) diff_t1_t2 from '||cTable1||' t1 full outer join '||cTable2||' t2 on(t1.'||cPK||'=t2.'||cPK||')';
    dbms_output.put_line(cSQL);
    end;then you can enclose the generated SQL with a select * from (..) where diff_t1_t2='!='
    It will give you something like:
    SELECT t1.*,
           t2.*,
           (CASE
               WHEN t1.c1 IS NULL THEN 'Missing in T1'
               ELSE NULL
            END) exists_t1,
           (CASE
               WHEN t2.c1 IS NULL THEN 'Missing in T2'
               ELSE NULL
            END) exists_t2,
           (CASE
               WHEN(   t1.C1 = t2.C1
                    OR (    t1.C1 IS NULL
                        AND t2.C1 IS NULL))
            AND    (   t1.C2 = t2.C2
                    OR (    t1.C2 IS NULL
                        AND t2.C2 IS NULL))
            AND    (   t1.C3 = t2.C3
                    OR (    t1.C3 IS NULL
                        AND t2.C3 IS NULL)) THEN '='
               ELSE '!='
            END
           ) diff_t1_t2
    FROM   T1 t1 FULL OUTER JOIN T2 t2 ON(t1.c1 = t2.c1)JV
    Edited by: user11268895 on Jun 16, 2010 8:25 AM
    Edited by: user11268895 on Jun 16, 2010 8:27 AM
    Edited by: user11268895 on Jun 16, 2010 8:29 AM

  • Trying to pivot based on a dynamically created query which generates XML data

    Hi there,
    Hope someone can help
    I'm trying to pivot row data into a pivot type result set where the records for a given employee are pivoted to a single row.
    To do this, I've declared a dynamic query to retrieve the GUID values of the different training course- the actual course names are full of SQL escape characters e.g. ', (,) which I thought might mess up the dynamically generated query
    I've got as far as writing
    DECLARE
    @employeeidsVARCHAR(10)
    DECLARE
    @coursesVARCHAR(max)
    DECLARE
    @queryVARCHAR(max)
    SELECT
      @courses=STUFF((SELECT 
    DISTINCT[TRAIN_ID]
    FROM  
    [Megapay_IWA].[dbo].[HRS_TRAINING]
    FORXMLPATH('')
    ),2,0,'')+']'
    SET
    @query=
    'SELECT * FROM
    (  SELECT t.TRAIN_TRAINING,
       EMPL_EMPLOYEE_ID
            FROM 
    [Megapay_IWA].[dbo].[HRSTRNDONE] as tc
    left  join  Megapay_IWA.dbo.PAYEMPL  as e on tc.TRND_ONRID = e.EMPL_EMPLOYEE_id
    left join [Megapay_IWA].[dbo].[HRS_TRAINING] as t on tc.TRND_TRAIN_ID =t.TRAIN_ID
    ) t
    PIVOT (COUNT(EMPL_EMPLOYEE_ID) FOR TRAIN_ID in
    +@courses+'))
    AS pvt'
    EXECUTE
    (@query)
    which generates a dynamic query along the following lines but how to I update the query to correctly read the train_id values in the xml
    SELECT * FROM
    (  SELECT t.TRAIN_TRAINING,
       EMPL_EMPLOYEE_ID
            FROM 
    [Megapay_IWA].[dbo].[HRSTRNDONE] as tc
    left  join  Megapay_IWA.dbo.PAYEMPL  as e on tc.TRND_ONRID = e.EMPL_EMPLOYEE_id
    left join [Megapay_IWA].[dbo].[HRS_TRAINING] as t on tc.TRND_TRAIN_ID =t.TRAIN_ID
    ) t
    PIVOT (COUNT(EMPL_EMPLOYEE_ID) FOR TRAIN_ID in
    <TRAIN_ID>F607BA64-BD24-4C6F-810E-001E7487FB4B</TRAIN_ID><TRAIN_ID>784EF318-628F-407E-8844-0049E3DD8F86</TRAIN_ID><TRAIN_ID>C7F3B365-7E6C-4CDF-9F0C-010207D1E493</TRAIN_ID><TRAIN_ID>7A82C4C1-5A9F-4EB0-9988-018405D3347A</TRAIN_ID><TRAIN_ID>E3FC88F5-AF5F-4D75-816A-02085190FC5C</TRAIN_ID><TRAIN_ID>BEB39D10-7887-494C-ADCC-0254A1514D06</TRAIN_ID><TRAIN_ID>6D870918-CFA1-4ADA-8427-049FF01902AC</TRAIN_ID><TRAIN_ID>61D1B40A-A9B6-4835-82C4-04FDCCAF7E6D</TRAIN_ID><TRAIN_ID>CA6D6B7-5ACA-4BE0-8A08-0EE87F77F10E</TRAIN_ID><TRAIN_ID>F86E6E93-544E-43F5-A97A-10E96834C781</TRAIN_ID><TRAIN_ID>EB898326-705F-4E70-B7BB-119B8953DFA9</TRAIN_ID><TRAIN_ID>491BFC77-0FA9-42C5-A255-11C49AA28CDD</TRAIN_ID><TRAIN_ID>C7A972FB-1E73-41FC-A4EF-12F5811C9853</TRAIN_ID><TRAIN_ID>3FD2CEE3-E85F-4624-87D7-13767D2DB391</TRAIN_ID><TRAIN_ID>F8A784C0-6E56-4769-92D2-1480BCAB2BEA</TRAIN_ID><TRAIN_ID>60D36A51-E642-40A2-A2F7-14D158B59781</TRAIN_ID><TRAIN_ID>67ED29A3-E2AD-42EC-8312-156084C0BB26</TRAIN_ID><TRAIN_ID>64B637B9-CC7D-47C8-9220-15D5FA76E65F</TRAIN_ID><TRAIN_ID>59B5D61C-4228-485D-89EE-185B74E42F3C</TRAIN_ID>
    Note I'm also fine with updating the dynamic query to generate a statement that generates a normal where in constraint e.g.
    PIVOT (COUNT(EMPL_EMPLOYEE_ID) FOR TRAIN_ID in
    ('F607BA64-BD24-4C6F-810E-001E7487FB4B','784EF318-628F-407E-8844-0049E3DD8F86')
    Thanks
    John

    Thanks guys, that helped immensely,
    For the record here is the slightly modified version [made generic to show the overall principle] that got it working for me in the end
    DECLARE @ColumnList VARCHAR(MAX) = '';
    DECLARE @query VARCHAR(max);
    WITH Data AS (
            SELECT columnname
             FROM    dbo.table
             SELECT         @ColumnList +='[' +  [columnname] +'],'
             FROM         Data;
    SET @ColumnList = STUFF(@ColumnList, 2, 0, '');
    SET @ColumnList = LEFT(@ColumnList, LEN(@ColumnList) - 1)
    --print @columnlist
    SET @query=
    'SELECT otherfields, ' +@ColumnList +' FROM
    (  SELECT   otherfields,columnname, datefield
             FROM        dbo.table
    ) t
    PIVOT (max(datefield) FOR [columnname] in (' +@ColumnList + ')
    ) AS pvt'
    execute (@query)

  • Complete novice needs help getting SQL Query into Crystal Reports XI

    Post Author: MissMarnie
    CA Forum: Data Connectivity and SQL
    So I was given an intro level web course and a monster reference guide in prep to format a report. One of our developers wrote me everything I need for the report into a SQL Query and now I'm supposed to format it in CR XII literally do not know what to do from here. I'm able to set up the correct server as a datasource, if that's useful, but I don't know how to make the querey into a bunch of formattable fields in  CR. If anyone can walk me through this, I'd be so grateful. I've attempted to look up SQL query in both the help and the book but I keep hitting a wall. The help dialog says things like "press this button" with no reference to what "this button" is. I'm sure it's obvious to the knowledgeable but I'm in a complete fog. Thanks in advance   

    Post Author: synapsevampire
    CA Forum: Data Connectivity and SQL
    IF you're trying to get assistance with setting up a query as the source for a report, try posting your Crystal version and the database type.
    Different software works differently.
    In CR 9 and above, under the connection to the database you'll see Add Command. Select that and you can paste the query in.
    As for not knowing how to generate a report, that requires experience, there's no generic solution of course..
    -k

  • Need to adjust SQL query for left outer join in Crystal Reports 2008.

    I need to change this SQL 2005 query.....
    SELECT     omnicell_anl.DeviceIDsLastMetricTable.member_id, omnicell_anl.DeviceIDsLastMetricTable.[Device Name],
                          omnicell_anl.DeviceIDsLastMetricTable.Account, omnicell_anl.labeledLastMetrics.PROPERTY_NAME,
                          omnicell_anl.labeledLastMetrics.latest_monitor_value
    FROM         omnicell_anl.DeviceIDsLastMetricTable LEFT OUTER JOIN
                          omnicell_anl.labeledLastMetrics ON omnicell_anl.DeviceIDsLastMetricTable.member_id = omnicell_anl.labeledLastMetrics.member_id
    WHERE
        omnicell_anl.labeledLastMetrics.PROPERTY_NAME = ?MyProperty
    To this query in Crystal Reports Report Writer:
    SELECT     omnicell_anl.DeviceIDsLastMetricTable.member_id, omnicell_anl.DeviceIDsLastMetricTable.[Device Name],
                          omnicell_anl.DeviceIDsLastMetricTable.Account, omnicell_anl.labeledLastMetrics.PROPERTY_NAME,
                          omnicell_anl.labeledLastMetrics.latest_monitor_value
    FROM         omnicell_anl.DeviceIDsLastMetricTable LEFT OUTER JOIN
                          omnicell_anl.labeledLastMetrics ON omnicell_anl.DeviceIDsLastMetricTable.member_id = omnicell_anl.labeledLastMetrics.member_id AND
                          omnicell_anl.labeledLastMetrics.PROPERTY_NAME = ?MyProperty
    I can't seem to get the left outer join function of Crystal Reports to emulate the same SQL query in SQL 2005.  Any ideas on how I can create this same query in Crystal 2008?
    Thanks,
    Dominic
    Edited by: Dominic Carissimi on Oct 28, 2008 7:55 PM
    Edited by: Dominic Carissimi on Oct 28, 2008 7:56 PM

    If you want the list of values for command level parameter then you need to add another command like
    select PropertyField from table
    and delete the links between this command and the existing command.
    Now go to field explorer and edit the command level parameter and make it as dynamic and add the property field from newly added command.
    Hope this helps!
    Raghavendra

Maybe you are looking for

  • Connectivity issues since upgrading to Snow Leopard

    Hello folks.  Sorry to dredge up bad memories, but I upgraded my old MacBook Pro (2.5 GHz Intel Core 2 Duo) from 10.5.8 to 10.6.3.  AirportX firmware update ran at the same time, now my network shows as connected, but I can't connect to mail or Inter

  • Safari 5.0.6 keeps crashing upon launch

    I no longer can launch Safari anymore.  It opens, hangs, goes to my home page (Google.com) and then promptly shuts down. Here is the problem report.  Any suggestions?  Thanks, Process:         Safari [141] Path:            /Applications/Safari.app/Co

  • SCC4 - settings not saved

    I need to open a QA system (Client Role = TEST) to change the current settings for an object. When I try to save the SCC4 client setting u201CCross-client Object changesu201D from u201CNo Changes to Repository and Cross-client Customizing Objectsu201

  • Messy eclipse 3.1 (WTE)

    dear friends, I�m hard trying to run an old web-app in the eclipse 3.1 - web tool for eclipse.... now, the last problem is the code base: every time I try to run te proect on the server, it points to a wrong document base.. . how to configure project

  • App for Plantronics Pro+ needed

    With all this technology, is there an app that will send all "alerts" (txt, email, phone, music, blah blah blah) to my Plantronics BT Pro+ earpiece? I want the phone itself to be silent and all activity to be transfered to my earpiece. Surely this is