Crosstab query using pure SQL only

Hi all,
Found a lot of threads on crosstab, but none seems to address what I need. I need to perform crosstab query using pure SQL only & the number of columns are dynamic. From a query, I obtained the below table:
Name Date Amount
Alex 2005-06-10 1000
Alex 2005-06-20 1000
Alex 2005-07-10 1000
Alex 2005-07-20 1000
Alex 2005-08-10 1000
Alex 2005-08-20 1000
John 2005-06-10 2000
John 2005-06-20 2000
John 2005-07-10 2000
John 2005-07-20 2000
John 2005-08-10 2000
John 2005-08-20 2000
And I need to transform it into:
Name 06-2005 07-2005 08-2005
Alex 2000 2000 2000
John 4000 4000 4000
Reason for the columns being dynamic is because they'll be a limit on the date ranges to select the data from. I'd have a lower & upper bound date say June-2005 to August-2005, which explains how I got the data from the above table.
Please advise.
Thanks!

Hi,
I couldn't resist the intellectual challenge of a pure SQL solution for a pivot table with a dynamic number of columns. As Laurent pointed out, a SQL query can only have a fixed number of columns. You can fake a dynamic number of columns, though, by selecting a single column containing data at fixed positions.
<br>
<br>
If it were me, I'd use a PL/SQL solution, but if you must have a pure SQL solution, here is an admittedly gruesome one. It shows the sum of all EMP salaries per department over a date range defined by start and end date parameters (which I've hardcoded for simplicity). Perhaps some of the techniques demonstrated may help you in your situation.
<br>
<br>
set echo off
set heading on
set linesize 100
<br>
select version from v$instance ;
<br>
set heading off
<br>
column sort_order noprint
column sal_sums format a80
<br>
select -- header row
  1        as sort_order,
  'DEPTNO' as DEPTNO ,
  sys_connect_by_path
    ( rpad
        ( to_char(month_column),
          10
      ' | '
    ) as sal_sums
from
    select
      add_months( first_month, level - 1 ) as month_column
    from
      ( select
          date '1981-01-01' as first_month,
          date '1981-03-01' as last_month,
          months_between( date '1981-03-01', date '1981-01-01' ) + 1 total_months
        from dual
    connect by level < total_months + 1
  ) months
where
  connect_by_isleaf = 1
connect by
  month_column = add_months( prior month_column, 1 )
start with
  month_column = date '1981-01-01'
union all
select -- data rows
  2 as sort_order,
  deptno,
  sys_connect_by_path( sum_sal, ' | ' ) sal_sums
from
  select
    dept_months.deptno,
    dept_months.month_column,
    rpad( to_char( nvl( sum( emp.sal ), 0 ) ), 10 ) sum_sal
  from
      select
        dept.deptno,
        reporting_months.month_column
      from
        dept,
        ( select
            add_months( first_month, level - 1 ) as month_column
          from
            ( select
                date '1981-01-01' as first_month,
                date '1981-03-01' as last_month,
                months_between( date '1981-03-01', date '1981-01-01' ) + 1 total_months
              from
                dual
          connect by level < total_months + 1
        ) reporting_months
    ) dept_months,
    emp
  where
    dept_months.deptno = emp.deptno (+) and
    dept_months.month_column = trunc( emp.hiredate (+), 'MONTH' )
  group by
    dept_months.deptno,
    dept_months.month_column
) dept_months_sal
where
  month_column = date '1981-03-01'
connect by
  deptno = prior deptno and
  month_column = add_months( prior month_column, 1 )
start with
  month_column = date '1981-01-01'
order by
  1, 2
<br>
VERSION
10.1.0.3.0
<br>
DEPTNO      | 81-01-01   | 81-02-01   | 81-03-01
10          | 0          | 0          | 0
20          | 0          | 0          | 0
30          | 0          | 2850       | 0
40          | 0          | 0          | 0
<br>
Now, if we substitute '1981-03-01' with '1981-06-01', we see 7 columns instead of 4
<br>
DEPTNO      | 81-01-01   | 81-02-01   | 81-03-01   | 81-04-01   | 81-05-01   | 81-06-01
10          | 0          | 0          | 0          | 0          | 0          | 2450
20          | 0          | 0          | 0          | 2975       | 0          | 0
30          | 0          | 2850       | 0          | 0          | 2850       | 0
40          | 0          | 0          | 0          | 0          | 0          | 0
<br>To understand the solution, start by running the innermost subquery by itself and then work your way outward.

Similar Messages

  • Crosstab query using  PL/SQL [HELP]

    hi all,
    i got this output after execute my query:
    week no | department | item | budget
    1 | 0901 | salary | 25000
    1 | 0901 | stationery | 5000
    1 | 5501 | salary | 45000
    2 | 0901 | salary | 25000
    2 | 5501 | salary | 25000
    2 | 5501 | stationery | 100
    i hope to get the output like below:
    dept/week no 1 2 3
    =========================================
    0901 30,000 25,000 800 (A)
    5501 45,000 25,100 100 (B)
    variance 45,000 70,000 70,800 (C)
    =========================================
    Grand total - 75,000 - 50,100 - (D)
    ======================================
    NOTE:
    the week is from week 1 until week 52, is it advisable to use looping or??.
    It is more than 2 departments and items as well. the user is allowed to passing in more than 1 selection of the items (salary,stationary,hardware and software, etc) to get this report.
    I need to display the output on the screen/spool into file after the execution.
    ==========
    Definition
    ===========
    Grant total (D1) by week =(A1 + B1)
    Variance (C1) for the 1st week of the year will always take the (B1) values as the based values for the next calculation. whereas (C2) = (C1) + (A2) and (C3) =(C2)+(A3) and the same formular apply up to week 52.
    the pivot method not a suitable solution to produce this output.
    anyone can suggest the shorter and more intelligent solution?
    this is very urgent, pls help!! thank

    You can get your basic data by,
    SELECT department, week_no, sum(budget) AS budget
      FROM your_table
    GROUP BY department, week_no;Then you'll just pivot the above data by week. Then you can use an analytic SUM() to get your weekly totals.
    WITH your_table AS (
    SELECT '0901' AS department, 1 AS week_no, 1000 AS budget FROM dual
    UNION ALL
    SELECT '1234' AS department, 1 AS week_no, 500 AS budget FROM dual)
    SELECT v.*,
           SUM(budget) OVER (PARTITION BY week_no) AS week_total
      FROM (
    SELECT department, week_no, sum(budget) AS budget
      FROM your_table
    GROUP BY department, week_no
    ORDER BY department, week_no
           )  v;I have to admit I'm a bit confused about your definition of variance.

  • Query used by SQL Server Management Pack for monitoring database backups

    I use SCOM 2012 R2 and the SQL Server Management Pack to monitor SQL Server database backups. I believe I am getting false positives. SCOM reports database are not backuped, while in fact they are. So I need to troubleshoot this. I suspect SCOM is querying
    the backup history in the msdb database. I want to know which query SCOM uses.
    I have tried looking in the monitor's definition but I suspect the query is embedded in the management pack files which are binary. I have also tried running a trace using the SQL Server Profiler on my test environment and overriding the interval to 60 seconds,
    but I don't see a relevant query being executed. I also don't see the alert reappear so I suspect SCOM does not honor the interval in a way I would expect.
    What query, or other method, does SCOM use to check database backups?
    Thanks in advance.

    Thank you both Ivan and Michael,
    I only saw your messages by email and didn't see your screen shot before I extracted the query myself. In my own queries I calculate the backup age in hours instead of days because of daily full backups. Perhaps It will be a good idea to create my own monitors
    from scratch like I used to do with Nagios.
    I will study the vbscripts and might create my own version which allows the query to be entered as an parameter and move all code to a .Net class which can be called from vbscript as an COM object. This way I hope to reduce the vbscript code to an minimum
    while keeping the flexibility of the SCOM Operations Console and the robustness of .Net. I suspect I want to make more non standard monitors in the future.
    Regards,
    Arjen

  • Parameter passing to custom SQL query using PL/SQL FUNCTION

    Hi
    In order to pass a parameter to the query in custom folder of a business area I created a function and mapped it to the Custome query using Discoverer Desktop. There is no error in mapping as the system does not throw any error. When I am inputting the Parameter for the input values everytime the query doesnot return any rows.
    Can anybody help in this regard

    Hi,
    I need to take the request Id as input from the user and then fetch only the data pertaining to that requet Id. As a lot of complex joins are involved I need to pass request id as parameter to the custome folder.
    The package i greated:
    CREATE OR REPLACE PACKAGE SETPARAM
    AS
    param1 varchar2(25);
    param2 varchar2(25);
    FUNCTION SET_PARAM1(p1 IN varchar2) RETURN NUMBER ;
    FUNCTION GET_PARAM1 RETURN varchar2;
    END SETPARAM;
    CREATE OR REPLACE PACKAGE BODY SETPARAM AS
    FUNCTION SET_PARAM1(p1 IN varchar2) RETURN NUMBER IS
    BEGIN
    fnd_client_info.set_org_context('138');
    param1 := p1;
    dbms_output.put_line(param1);
    RETURN 1;
    END;
    FUNCTION GET_PARAM1 RETURN varchar2 AS
    BEGIN
    RETURN param1;
    END;
    END SETPARAM;
    I registered the set_param1 function as a pl/sql function in discoverer admin.
    This function is called on the condition associated with the parameter in Discoverer Desktop when i run the report.
    In the custom folder query i have this piece in the where clause
    WHERE tnfo.request_id = NVL(APPS.SETPARAM.GET_PARAM1,7383588)
    And everytime i get the data pertaining to request id =7383588,
    Please suggest where i went wrong
    thanks
    Ashwini

  • Optimizing an SQL Query using Oracle SQL Developer

    Hi ,
    Currently i am using Oracle SQL Developer as my Database IDE .
    Is it possible to use Orqcles SQLDeveloper for the purpose of Optimizing an SQL Query ??
    For example assume i am having a query as :
    Select from Tranac_Master where CUST_STATAUS='Y' and JCC_REPORT='N'*
    Could anybody please tell me how can i use Oracle SQL Developer to optimize this query or any other SQL queries ??
    Please share your ideas , thanks in advance .

    1. Your query looks very simplistic as it is, so I fail to see how you can better optimise it (unless 'Tranac_Master' is a view, in which case I'd need to see the view details).
    2. No tool can automagically optimise your SQL to any degree of practical use. Very minor adjustments may be possible automatically, but really it is a question of you knowing your data & database design accurately, and then you applying your expert knowledge to tune it.

  • Query using the SQL 'go' command  on a JAVA code

    Hi,
    I am trying to create a new database on MS SQL and at the same time verify whether the data base exist already and then add a new table. The query statement works well on the query windows on MS SQL, but when the query is place using a JAVA code it gives the following error:
    java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'go'.
    java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'go'.
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbc.SQLExecDirect(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbcStatement.execute(Unknown Source)
         at sun.jdbc.odbc.JdbcOdbcStatement.executeQuery(Unknown Source)
         at DataBaseCreator.main(DataBaseCreator.java:30)
    I have to add that if I only query: "CREATE DATABASE NameOfDatabase" the new data base is created without a problem using JAVA, but when I try to use the following query, I got the error message.
    "USE Master "
                        + "IF EXISTS (SELECT * FROM SysDatabases WHERE NAME='DatesTemps') "
                        + " DROP DATABASE DatesTemps"
                        + " go "
                        + " CREATE DATABASE DatesTemps22 "
                        + " go"
                        + " USE DatesTemps "
                        + " CREATE TABLE Fable ( "
                        + " FableID INT NOT NULL CONSTRAINT FablePK PRIMARY KEY NONCLUSTERED, "
                        + " Title VARCHAR(50) NOT NULL, "
                        + " Moral VARCHAR(100) NOT NULL, "
                        + " FableText VARCHAR(1536) NOT NULL, "
                        + " BlobType CHAR(3) NULL DEFAULT 'doc', "
                        + " Blob IMAGE NULL DEFAULT NULL )"
    If it is useful my complete code is the following, I appreciate in advance your comments.
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    public class DataBaseCreator {
         public static void main (String[] args)
              Connection Time =null;
              Statement stmt = null;
              String data = "jdbc:odbc:DataBaseCreation";
              try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Time= DriverManager.getConnection(data,"","");
                   stmt = Time.createStatement();
                   //String query;
                   //java.sql.Timestamp ts1 = new java.sql.Timestamp(((3*60)+58)*60*1000);
              // System.out.println(ts1 + " This is a Time Stamp");
              ResultSet rec = stmt.executeQuery(
                        "USE Master "
                        + "IF EXISTS (SELECT * FROM SysDatabases WHERE NAME='DatesTemps') "
                        + " DROP DATABASE DatesTemps"
                        + " go "
                        + " CREATE DATABASE DatesTemps22 "
                        + " go"
                        + " USE DatesTemps "
                        + " CREATE TABLE Fable ( "
                        + " FableID INT NOT NULL CONSTRAINT FablePK PRIMARY KEY NONCLUSTERED, "
                        + " Title VARCHAR(50) NOT NULL, "
                        + " Moral VARCHAR(100) NOT NULL, "
                        + " FableText VARCHAR(1536) NOT NULL, "
                        + " BlobType CHAR(3) NULL DEFAULT 'doc', "
                        + " Blob IMAGE NULL DEFAULT NULL )"
              catch( Exception e )
                        System.err.println( e );
                        e.printStackTrace();
              finally
                        try
                             stmt.close();
                             Time.close();
              catch( Exception e )
                        System.err.println( e );
    }

    Ok, first of all thanks for your answer, now what I want to do is the following:
    1) I need to input ((retrieve) every minute some data (Date and Temperature), that I will get from and external device, this is not part of this code.
    2) I want to store that data (Date and Temp) on a data base, here where I need the command to create the data base and to verify whether that data base already exists. In case it has already been created then create new table(s) on it. If it doesn't exist then create and then create new tables.
    3) Each Day (at yyyy mm dd 00:00:00:000 will create a new table, and the name of this table will be yyyymmdd.
    4) Then every minute the java code will retrieve the data and add it to the table in the data base.
    5) That will be a close loop that will be running until the user interrupt it.
    I haven't make the communication code yet, in order to test my code I was thinking to retrieve the data from another data base. This would be just to verify that the JAVA sequence is able to retrieve the data every minute and create new data base and tables.
    For the record I am able to send the queries and retrieve information from SQL running the code in eclipse, that will cover your first observation.
    I am quite new in the forum I am sorry I didn't get the use of code tags.
    Sorry again as I said I am quite new on this, what's a DDL statement.
    Thanks.

  • Querying using Native SQL

    Hi Pals,
    I have a requirement which I would like to brief.
    I have an internal table with columns FIELD1 and FIELD2. For all the values in FIELD1 I have to query a table MSI(which does not form a part of the R/3 framework) through Native SQL statement and get the corresponding values for FIELD2.
    Could anybody suggest how I must proceed writing my statements between EXEC and ENDEXEC.
    Do I have to query the database table for each entry in my internal table or is it possible to use for all entries in my SQL statemnt.
    Your inputs would be highly appreciated.
    Thank You in advance.
    Regards,
    Gayathri N.

    Hai Gayathri
    check this document
    EXEC SQL.
    Addition
    ... PERFORMING form
    Effect
    Executes the Native SQL command enclosed by the statements EXEC SQL and ENDEXEC . In contrast to Open SQL , addressed database tables do not have to be known to the ABAP/4 Dictionary and the ABAP/4 program does not have to contain appropriate TABLES statements.
    Example
    Create the table AVERI_CLNT :
    EXEC SQL.
      CREATE TABLE AVERI_CLNT (
             CLIENT   CHAR(3)  NOT NULL,
             ARG1     CHAR(3)  NOT NULL,
             ARG2     CHAR(3)  NOT NULL,
             FUNCTION CHAR(10) NOT NULL,
             PRIMARY KEY (CLIENT, ARG1, ARG2)
    ENDEXEC.
    With Native SQL commands, passing data between an ABAP/4 program and the database is achieved using host variables . A host variable is an ABAP/4 variable prefixed by a "*" in the Native SQL statement.
    Example
    Display a section of the table AVERI_CLNT :
    DATA: F1(3), F2(3), F3(3).
    F3 = ' 1 '
    EXEC SQL.
      SELECT CLIENT, ARG1 INTO :F1, :F2 FROM AVERI_CLNT
             WHERE ARG2 = :F3
    ENDEXEC.
    WRITE: / F1, F2.
    To simplify the spelling of INTO lists in the SELECT command, you can specify a single structure as the target area as in Open SQL .
    Example
    Display a section of the table AVERI_CLNT :
    DATA: BEGIN OF WA,
            CLIENT(3), ARG1(3), ARG2(3),
          END OF WA.
    DATA  F3(3).
    F3 = ' 1 '
    EXEC SQL.
      SELECT CLIENT, ARG1 INTO :WA FROM AVERI_CLNT
             WHERE ARG2 = :F3
    ENDEXEC.
    WRITE: / WA-CLIENT, WA-ARG1.
    Notes
    In contrast to Open SQL , a client field in Native SQL is a field like any other and must be specified explicitly in calls.
    Authorization checks cannot be properly realized in EXEC SQL . You should perform these in the program.
    When you start the R/3 System, a CONNECT to the current database is executed automatically. An explicit CONNECT is unnecessary.
    A Native SQL command can (but does not have to) end with a ";". Under no circumstances should it end with a ".".
    Some database systems allow upper and lower case in table names and field names. If you want to take advantage of this, you must ensure that the spelling of names is correct. To enable entry of lower case letters in names in the ABAP/4 editor, you must set the attribute for upper/lower case in the report.
    Since there are no arrays in ABAP/4 , array operations are not possible in Native SQL . If the result of a SELECT command is a table, you can read this table line by line either with the Native SQL command FETCH or with the addition ... PERFORMING form .
    Unlike in ABAP/4 programs, the character " in a Native SQL statement does not introduce a comment until the end of the editor line.
    Addition
    ... PERFORMING form
    Effect
    If the result of a SELECT command is a table, you can read this table line by line in a processing loop. The subroutine form is called once for each line. In this subroutine, you can leave the loop by using EXIT FROM SQL . If the result of the selection is a single record, the subroutine is called only once.
    Example
    Display a section of the table AVERI_CLNT :
    DATA: F1(3), F2(3), F3(3).
    F3 = ' 1 '
    EXEC SQL PERFORMING WRITE_AVERI_CLNT.
      SELECT CLIENT, ARG1 INTO :F1, :F2 FROM AVERI_CLNT
             WHERE ARG2 = :F3
    ENDEXEC.
    FORM WRITE_AVERI_CLNT.
      WRITE: / F1, F2.
    ENDFORM.
    Note
    This addition is allowed only with a SELECT command.
    Related SELECT , INSERT , UPDATE , MODIFY , DELETE , OPEN CURSOR , FETCH , CLOSE CURSOR, COMMIT WORK and ROLLBACK WORK .
    go to se38
    type 'EXEC' and put cursor on 'EXEC' press f1-function key
    then you get help for EXEC
    Thanks & regards
    Sreenivasulu P
    Message was edited by: Sreenivasulu Ponnadi

  • JDBC Query using PL/SQL

    I have gotten this to work in my Reports class but can not get this to work at my company. Basically I'm trying to use the JDBC query in Report Builder.
    Here is my Ref Cursor Code:
    CREATE OR REPLACE PACKAGE SCOTT.types is
    type sqlcur is REF cursor;
    end;
    Here is my Pl/SQL function:
    CREATE OR REPLACE FUNCTION SCOTT.test return Scott.types.sqlcur is
    c1 Scott.types.sqlcur;
    begin
    open c1 for select * from scott.emp;
    return c1;
    end;
    I can get this to work in SQL Plus by doing the following:
    var r refcursor
    exec :r := test;
    print r When I go into Reports Builder->JDBC query I connect to the SCOTT db using tiger as the password. I type in the function name TEST and get the error "wrong number or types of arguments in call TEST". I have tried "call TEST" but that doesnt work either. If I use "call TEST" I get an error saying it expected characters ":=(@" etc....
    I know my connection works because I can do a "select * from emp" and get results. Can anyone get this to work?
    I'm running Report Builder 9.0.2.0.3
    I have done multiple searches on this issue and most responses point someone to links that dont work or documentation. I have read them and my code above should work but doesnt........Please put some real examples or code that works with the "Scott" schema.
    Thanks

    hi Shawn
    When running jdbc quesry based on SP with Oracle DB, the first parameter of the store procedure should be of ref cursor type and it shall be a OUT parameter.
    For example:
    CREATE OR REPLACE PACKAGE jdbcpdspkg AS
    TYPE Empcur IS ref cursor ;
    procedure proc_with_param      (p_emp_cv out jdbcpdspkg .empcur, p1 in number, p2 in number , p3 in number, p4 in number , p5 in number) ;
    Thanks
    Rohit

  • Tree query using XML SQL

    Hi,
    Any ideas or code samples of how we could use the XML SQL Utility
    to do a tree structure, like the following:
    <GROUP id="grp1">
    <ITEM> item 1 </ITEM>
    <ITEM> item 2 </ITEM>
    <GROUP id="grp2">
    <ITEM> item 3 </ITEM>
    <ITEM> item 4 </ITEM>
    </GROUP>
    <ITEM> item 5 </ITEM>
    </GROUP>
    Thanks,
    Cyril.
    null

    Hi Mark,
    To a certain extent one can modify the xml generated by
    manipulating the query and by using some of the tag name
    customizations which the XSU allows. Unfortunately, what you
    want to create will take more than that; you will have to use
    XSLT - xml transformation language, part of XSL. You will find
    and XSL processor packaged with the oracle xml parser v2 (see
    oraxsl). You can find more info on XSLT at www.w3c.org
    Mark Fortner (guest) wrote:
    : I have an example similar to his:
    : Given a resultset in the form:
    : Company Department User
    : Oracle XML Dev John Smith
    : Oracle XML Dev Jane Smith
    : Oracle Mgmt Larry Ellison
    : Sun Project X Jane Doe
    : Sun Mgmt Scott McNealy
    : which usually results in XML like this
    : <rowset>
    : <row id=1>
    : <Company>Oracle</Company>
    : <Department>XML Dev</Department>
    : <User>John Smith</User>
    : </row>
    : </rowset>
    : how do I get it to look like this?
    : <JTree>
    : <Oracle>
    : <XML Dev>
    : <Jane Smith/>
    : <John Smith/>
    : </XML Dev>
    : <Mgmt>
    : <Larry Ellison/>
    : </Mgmt>
    : </Oracle>
    : <Sun>
    : <Project X>
    : <Jane Doe/>
    : </Project X>
    : <Mgmt>
    : <Scott McNealy/>
    : </Mgmt>
    : </Sun>
    : </JTree>
    : Oracle XML Team wrote:
    : : Hi Cyril,
    : : Your question is a bit vague. Do you have a table which
    you
    : : are trying to query and get the result in the following
    : format?
    : : If these is the case please give me the description of the
    : table
    : : or the view.
    : : The other thing to keep in mind is that even if the XSU
    : can't
    : : give you the XML data in the exactly the format you want, you
    : can
    : : always use XSLT to transform the XML doc generated by the XSU
    : to
    : : the desired XML doc.
    : : Cyril Dunnion (guest) wrote:
    : : : Hi,
    : : : Any ideas or code samples of how we could use the XML SQL
    : : Utility
    : : : to do a tree structure, like the following:
    : : : <GROUP id="grp1">
    : : : <ITEM> item 1 </ITEM>
    : : : <ITEM> item 2 </ITEM>
    : : : <GROUP id="grp2">
    : : : <ITEM> item 3 </ITEM>
    : : : <ITEM> item 4 </ITEM>
    : : : </GROUP>
    : : : <ITEM> item 5 </ITEM>
    : : : </GROUP>
    : : : Thanks,
    : : : Cyril.
    : : Oracle Technology Network
    : : http://technet.oracle.com
    Oracle Technology Network
    http://technet.oracle.com
    null

  • Linked server query using Dynamic SQL

    I have a Linked server query that takes forever to run. WHen I hardcode the acct# it runs fast. However I want these acct numbers int he where clause to be generated dynamically. For eg: below is what I need:
    --Get the 11 Loans from this Table A From the FIRST QUERY
    --- Plug those loans numbers in the second query  In the WHERE Clause eg should looks like  where  ACCT in (1,2,3,5)
    DECLARE
    @sSQL varChar(MAX)
    SET @sSQL
    =
    ' SELECT
    [Loan] FROM TableA D
    EXECUTE(@sSQL)
    --2ND QUERY 
    DECLARE
    @sSQL1 varChar(MAX)
    SET @sSQL1
    ='
    SELECT Field1, 
    Field2,
    Field3,
    Field4,
    Field5
       FROM LinkedServer.Dbaname.dbo.TableB a
    where ACCT in ''('''
    +(@sSQL)
    +
    ''')'''--- This needs to look like  where  ACCT in (1,2,3,5)
    select
    @sSQL1

    Ok, so use this.. instead of your first statement.
    DECLARE @sSQL NvarChar(MAX), @output NVARCHAR(100), @ParmDefinition nvarchar(500);
    SET @ParmDefinition = N'@sqlout NVARCHAR(100) OUTPUT'
    SET @sSQL = N'SELECT DISTINCT @sqlout = STUFF((SELECT '',''+CAST(S2.loan AS VARCHAR(100))
    FROM tableA S2
    FOR XML PATH('''')), 1, 1, '''')
    FROM tableA S1'
    EXECUTE sp_executesql @sSQL, @parmdefinition, @sqlout = @output OUTPUT
    and use @output instead of @sSQL in the second statement.
    You can read about STUFF command @
    http://sqlsaga.com/sql-server/how-to-concatenate-rows-into-one-row-using-stuff/.
    Good Luck :)
    Visit www.sqlsaga.com for more t-sql code snippets or BI related how to's.

  • Pure SQL of Select query on multiple tables in DB Adapter

    I am trying use pure sql approach for a custom sql query on multiple tables for a DB adapter by modifying toplink_mappings.xml. But i am not getting other tables in my xsd. Please help.

    hi Ravi,
    can you pls be a bit clear? what is this about? where you are using?
    thanks,
    sneha.

  • DB Adapter Pure Sql Option urgent

    Hi All,
    I have query like this .
    select
    supp.segment1 supplier_number,
    supp.vendor_name supplier_name,
    ph.segment1 po_number,
    ph.org_id,
    ph.creation_date po_date,
    pl.line_num po_line_number,
    pl.unit_price,
    pl.quantity line_quantity,
    pl.line_type,
    pl.item_number,
    pl.item_description,
    pl.UNIT_MEAS_LOOKUP_CODE UOM,
    pll.shipment_num po_shipment_number,
    pll.shipment_type,
    pll.ship_to_organization_code,
    pll.ship_to_location_code,
    pll.quantity shipment_quantity,
    pll.QUANTITY_ACCEPTED shipment_quantity_accepted,
    pll.QUANTITY_BILLED shipment_quantity_billed,
    pll.QUANTITY_CANCELLED shipment_quantity_cancelled,
    pll.QUANTITY_RECEIVED shipment_quantity_received,
    pll.QUANTITY_REJECTED shipment_quantity_rejected,
    pll.need_by_date,
    nvl(pll.inspection_required_flag,'N'), -- if its Yes then ites 4 Way Matching
    nvl(pll.receipt_required_flag,'N'), -- If Its Yes then its 3 Way Matching
    decode(nvl(pll.inspection_required_flag,'N'),'Y','4 WAY MATCHING',
    decode(nvl(pll.receipt_required_flag,'N'),'Y','3 WAY MATCHING', '2 WAY MATCHING'))
    matching_type,
    pll.qty_rcv_tolerance,
    pll.qty_rcv_exception_code,
    pll.category item_category,
    decode(pll.match_option,'P','Purchase Order','Receipt') Invoice_matching_option,
    pll.AMOUNT_RECEIVED shipment_amount_received,
    pll.AMOUNT_BILLED shipment_amount_billed,
    pll.amount_cancelled shipment_amount_cancelled,
    pll.amount_accepted shipment_amount_accepted,
    pll.amount_rejected shipment_amount_rejected,
    pd.distribution_num po_distribution_number,
    pd.amount_billed dist_amount_billed,
    pd.destination_context dist_destination,
    pd.DESTINATION_SUBINVENTORY,
    pd.quantity_ordered dist_quantity_ordered,
    pd.quantity_delivered dist_quantity_delivered,
    pd.quantity_cancelled dist_quantity_cancelled,
    pd.quantity_billed dist_quantity_billed,
    pd.amount_ordered dist_amount_ordered,
    pd.amount_delivered dist_amount_delivered,
    pd.amount_cancelled dist_amount_cancelled
    from
    po_headers_v ph,
    po_lines_v pl,
    po_line_locations_v pll,
    po_distributions_v pd,
    ap_suppliers supp,
    ap_supplier_sites_all supp_site
    where
    ph.authorization_status = 'APPROVED' -- Po Must be Approved
    and ph.po_header_id = pl.po_header_id
    and ph.closed_code = 'OPEN' --PO is still Open
    and pl.po_line_id = pll.po_line_id
    and pll.line_location_id = pd.line_location_id
    and ph.vendor_id = supp.vendor_id
    and ph.vendor_site_id = supp_site.vendor_site_id
    and pl.cancel_flag = 'N' --PO Line is not Cancelled
    and pl.closed_flag = 'N' --PO Line is Still Open
    and pll.approved_flag = 'Y' --Shipment is Approved
    and nvl(pll.cancel_flag,'N') = 'N' --Shipment is not cancelled
    and pll.closed_code = 'OPEN' --Shipment is still Open
    Iam trying to use pure sql option , i have pasted the modified query in this way below >
    select
    supp.segment1 supplier_number,
    supp.vendor_name supplier_name,
    ph.segment1 po_number,
    ph.org_id,
    ph.creation_date po_date,
    pl.line_num po_line_number,
    pl.unit_price,
    pl.quantity line_quantity,
    pl.line_type,
    pl.item_number,
    pl.item_description,
    pl.UNIT_MEAS_LOOKUP_CODE UOM,
    pll.shipment_num po_shipment_number,
    pll.shipment_type,
    pll.ship_to_organization_code,
    pll.ship_to_location_code,
    pll.quantity shipment_quantity,
    pll.QUANTITY_ACCEPTED shipment_quantity_accepted,
    pll.QUANTITY_BILLED shipment_quantity_billed,
    pll.QUANTITY_CANCELLED shipment_quantity_cancelled,
    pll.QUANTITY_RECEIVED shipment_quantity_received,
    pll.QUANTITY_REJECTED shipment_quantity_rejected,
    pll.need_by_date,
    nvl(pll.inspection_required_flag,'N'), -- if its Yes then ites 4 Way Matching
    nvl(pll.receipt_required_flag,'N'), -- If Its Yes then its 3 Way Matching
    decode(nvl(pll.inspection_required_flag,'N'),'Y','4 WAY MATCHING',
    decode(nvl(pll.receipt_required_flag,'N'),'Y','3 WAY MATCHING', '2 WAY MATCHING'))
    matching_type,
    pll.qty_rcv_tolerance,
    pll.qty_rcv_exception_code,
    pll.category item_category,
    decode(pll.match_option,'P','Purchase Order','Receipt') Invoice_matching_option,
    pll.AMOUNT_RECEIVED shipment_amount_received,
    pll.AMOUNT_BILLED shipment_amount_billed,
    pll.amount_cancelled shipment_amount_cancelled,
    pll.amount_accepted shipment_amount_accepted,
    pll.amount_rejected shipment_amount_rejected,
    pd.distribution_num po_distribution_number,
    pd.amount_billed dist_amount_billed,
    pd.destination_context dist_destination,
    pd.DESTINATION_SUBINVENTORY,
    pd.quantity_ordered dist_quantity_ordered,
    pd.quantity_delivered dist_quantity_delivered,
    pd.quantity_cancelled dist_quantity_cancelled,
    pd.quantity_billed dist_quantity_billed,
    pd.amount_ordered dist_amount_ordered,
    pd.amount_delivered dist_amount_delivered,
    pd.amount_cancelled dist_amount_cancelled
    from
    po_headers_v ph,
    po_lines_v pl,
    po_line_locations_v pll,
    po_distributions_v pd,
    ap_suppliers supp,
    ap_supplier_sites_all supp_site
    where
    ph.authorization_status = 'APPROVED'
    and ph.po_header_id = ?
    and ph.closed_code = 'OPEN'
    and pl.po_line_id = ?
    and pll.line_location_id = ?
    and ph.vendor_id = ?
    and ph.vendor_site_id = ?
    and pl.cancel_flag = 'N'
    and pl.closed_flag = 'N'
    and pll.approved_flag = 'Y'
    and nvl(pll.cancel_flag,'N') = 'N'
    and pll.closed_code = 'OPEN'
    My Question is : The Pasted modified query is correct ???, and this type of below
    nvl(pll.inspection_required_flag,'N'), -- if its Yes then ites 4 Way Matching
    nvl(pll.receipt_required_flag,'N'), -- If Its Yes then its 3 Way Matching
    decode(nvl(pll.inspection_required_flag,'N')
    Is Allowed ???????
    Edited by: anantwag on Apr 11, 2011 3:01 AM

    yeah , i was getting some error for that "--" but then i changed the query and now it does not have "---"
    But i have a question here the xsd generated is like this ...
    and query contains nvl(pll.cancel_flag,'N') which in xsd looks like below.
    <xs:element name="nvl" type="xs:string" nillable="true"/>
    <xs:element name="nvl" type="xs:string" nillable="true"/>
    <?xml version = '1.0' encoding = 'UTF-8'?>
    <xs:schema targetNamespace="http://xmlns.oracle.com/pcbpel/adapter/db/DBSelect" xmlns="http://xmlns.oracle.com/pcbpel/adapter/db/DBSelect" elementFormDefault="qualified" attributeFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="DBSelectInput" type="DBSelectInput"/>
    <xs:complexType name="DBSelectInput">
    <xs:sequence>
    <xs:element name="arg1" type="xs:string" nillable="true"/>
    <xs:element name="arg2" type="xs:string" nillable="true"/>
    <xs:element name="arg3" type="xs:string" nillable="true"/>
    <xs:element name="arg4" type="xs:string" nillable="true"/>
    <xs:element name="arg5" type="xs:string" nillable="true"/>
    </xs:sequence>
    </xs:complexType>
    <xs:element name="DBSelectOutputCollection" type="DBSelectOutputCollection"/>
    <xs:complexType name="DBSelectOutputCollection">
    <xs:sequence>
    <xs:element name="DBSelectOutput" type="DBSelectOutput" minOccurs="0" maxOccurs="unbounded"/>
    </xs:sequence>
    </xs:complexType>
    <xs:complexType name="DBSelectOutput">
    <xs:sequence>
    <xs:element name="supplier_number" type="xs:string" nillable="true"/>
    <xs:element name="supplier_name" type="xs:string" nillable="true"/>
    <xs:element name="po_number" type="xs:string" nillable="true"/>
    <xs:element name="ph_org_id" type="xs:string" nillable="true"/>
    <xs:element name="po_date" type="xs:string" nillable="true"/>
    <xs:element name="po_line_number" type="xs:string" nillable="true"/>
    <xs:element name="pl_unit_price" type="xs:string" nillable="true"/>
    <xs:element name="line_quantity" type="xs:string" nillable="true"/>
    <xs:element name="pl_line_type" type="xs:string" nillable="true"/>
    <xs:element name="pl_item_number" type="xs:string" nillable="true"/>
    <xs:element name="pl_item_description" type="xs:string" nillable="true"/>
    <xs:element name="UOM" type="xs:string" nillable="true"/>
    <xs:element name="po_shipment_number" type="xs:string" nillable="true"/>
    <xs:element name="pll_shipment_type" type="xs:string" nillable="true"/>
    <xs:element name="pll_ship_to_organization_code" type="xs:string" nillable="true"/>
    <xs:element name="pll_ship_to_location_code" type="xs:string" nillable="true"/>
    <xs:element name="shipment_quantity" type="xs:string" nillable="true"/>
    <xs:element name="shipment_quantity_accepted" type="xs:string" nillable="true"/>
    <xs:element name="shipment_quantity_billed" type="xs:string" nillable="true"/>
    <xs:element name="shipment_quantity_cancelled" type="xs:string" nillable="true"/>
    <xs:element name="shipment_quantity_received" type="xs:string" nillable="true"/>
    <xs:element name="shipment_quantity_rejected" type="xs:string" nillable="true"/>
    <xs:element name="pll_need_by_date" type="xs:string" nillable="true"/>
    <xs:element name="nvl" type="xs:string" nillable="true"/>
    <xs:element name="nvl" type="xs:string" nillable="true"/>
    <xs:element name="matching_type" type="xs:string" nillable="true"/>
    <xs:element name="pll_qty_rcv_tolerance" type="xs:string" nillable="true"/>
    <xs:element name="pll_qty_rcv_exception_code" type="xs:string" nillable="true"/>
    <xs:element name="item_category" type="xs:string" nillable="true"/>
    <xs:element name="Invoice_matching_option" type="xs:string" nillable="true"/>
    <xs:element name="shipment_amount_received" type="xs:string" nillable="true"/>
    <xs:element name="shipment_amount_billed" type="xs:string" nillable="true"/>
    <xs:element name="shipment_amount_cancelled" type="xs:string" nillable="true"/>
    <xs:element name="shipment_amount_accepted" type="xs:string" nillable="true"/>
    <xs:element name="shipment_amount_rejected" type="xs:string" nillable="true"/>
    <xs:element name="po_distribution_number" type="xs:string" nillable="true"/>
    <xs:element name="dist_amount_billed" type="xs:string" nillable="true"/>
    <xs:element name="dist_destination" type="xs:string" nillable="true"/>
    <xs:element name="pd_DESTINATION_SUBINVENTORY" type="xs:string" nillable="true"/>
    <xs:element name="dist_quantity_ordered" type="xs:string" nillable="true"/>
    <xs:element name="dist_quantity_delivered" type="xs:string" nillable="true"/>
    <xs:element name="dist_quantity_cancelled" type="xs:string" nillable="true"/>
    <xs:element name="dist_quantity_billed" type="xs:string" nillable="true"/>
    <xs:element name="dist_amount_ordered" type="xs:string" nillable="true"/>
    <xs:element name="dist_amount_delivered" type="xs:string" nillable="true"/>
    <xs:element name="ph" type="xs:string" nillable="true"/>
    <xs:element name="pl" type="xs:string" nillable="true"/>
    <xs:element name="pll" type="xs:string" nillable="true"/>
    <xs:element name="pd" type="xs:string" nillable="true"/>
    <xs:element name="supp" type="xs:string" nillable="true"/>
    <xs:element name="OPEN" type="xs:string" nillable="true"/>
    </xs:sequence>
    </xs:complexType>
    </xs:schema>
    Please help me out as, if the same thing will not work then i have to wrap the same query in the stored Procedure.

  • NVARCHAR (MAX) TO PRINT DYNAMIC SQL QUERY TO A SQL FILE

    Hi 
    I have a requirement where i need to write an SP which would construct a huge query using dynamic SQL and save the Dynamic query to a file. 
    The Dynamic SQL Variable I am using as @NVARCHAR(MAX) but since the query being built is large (>4000 characters), I am not able to select it into a table. PRINT @SQL prints the whole query but SELECT @SQL prints only upto 4000 characterrs. 
    And I need to save this huge dynamix sql to a file using the SP.
    Any thoughts as to how i can achieve this?
    Rajiv

    This is a know problem with dynamic SQL nvarchar(max) concatenation.
    See below for correct assembly of large SQL strings:
    CREATE table #temp(qry nvarchar(max));
    declare @cmd nvarchar(max);
    SELECT @cmd=CONCAT(CONVERT(nvarchar(max),N'SELECT '),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),REPLICATE (N'A',4000)),
    CONVERT(nvarchar(max),N'FROM SYS.TABLES'));
    insert into #temp SELECT @cmd;
    select * from #temp;
    select len(qry), datalength(qry) from #temp;
    -- 16022 32044
    drop table #temp;
    Dynamic SQL:  http://www.sqlusa.com/bestpractices/dynamicsql/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Create windows folder with PL/SQL only

    Hi
    I need to create a folder using PL/SQL only.
    We are using Oracle 10.2.0.1.0
    Thanks.

    No can do. Not with PL/SQL alone. You'd need a Java Stored Procedure and even then, it would create folders on the server.
    Why would you use a database for OS administration?
    Message was edited by:
    maaher

  • Check query used to create system views

    Hi Group,
    I would like to know if there is any way to check the TSQL query used by SQL to create system views. I know for user created views, you can open it in Designer or script the view. Use SQL 2012 as an example when selelcting the top 1000 records no underlyng
    query is visible.
    Thanks and Regards,

    You can see most of them using sys.all_objects and sys.system_sql_modules.  For example
    select o.name, m.definition
    from sys.system_sql_modules m
    inner join sys.all_objects o on m.object_id = o.object_id
    where o.name = 'dm_exec_requests'
    Be very careful that you don't ever run the code that creates the view.  There are additional tricks behind the scene that give some system views special actions.  So if you run the code, your code might not work the same way as the original system
    view.
    Also, anything which is not documented can be changed by Microsoft at any time.
    Tom

Maybe you are looking for

  • SQL statements inside BPEL Assign-Copy

    Hi, I am trying to take the contents of a string variable and substring it using SQL statements such as 'substr', 'decode' and 'instr', then copying the output onto another variable (within an Assign/Copy operation) to eventually pass it on to a tabl

  • File on server

    Hi I have a file on a server called test.exe,say. The directory structure on the server is as follows:                                                                -test                                                                         -dir1

  • IMac not COMPLETELY powering down...

    Morning all... I upgraded my 24" iMac (bought Jan 2007) to Leopard on Saturday, and apart from a few minor software funnies, it seemed to go OK. I just upgraded - not archive and install or anything complicated like that. The problem I now have is th

  • Kernel panic after replacing hard drive in Powerbook 17"

    I need help with a kernel panic that won't even let me start up. Here's a detailed account of what happened: The hard drive in my Powerbook 17" recently failed. Since it is out of warranty anyway, I decided to try to replace it myself. I found a good

  • G5 dual 2.7 powers on but no boot chime, video, keyboard activity

    Hello: I have a Power Mac G5 dual 2.7 from late 2005 w/ 2 GB RAM and no hard drive. Clearly, I won't be able to boot without a system. I bought it without the hard drive, thinking I'd install my own but test with a universal Tiger disk first. The pro