Query Regarding Native SQL

Hello Friends,
   I am having a requirement to fetch the records from 3 tables( Using inner join)
   into an internal table but I am facing a difficulty that I need to fetch the records from this table with entirely different conditions and I need to use ' UNION ALL' Command to fetch the records from the database. For Eg.
I have to write two select statement....
Select <f1> <f2> <f3> <f4>
from <t1> join <t2> join <t3>
into table ITAB
where <Cond. 1>
Select <f1> <f2> <f3> <f4>
from <t1> join <t2> join <t3>
appending table ITAB
where <Cond. 2>
But this is taking two much time... So the user told me to use native SQL to combine this two statement with UNION ALL.. I am using database DB2 Can anyone help me regarding this.
Thanks,
Navneet

HI,
Info in help is good to understand better. Below is the
same for you understanding.
... FROM tabref1 [INNER] JOIN tabref2 ON cond
Effect
The data is to be selected from transparent database tables and/or views determined by tabref1 and tabref2. tabref1 and tabref2 each have the same form as in variant 1 or are themselves Join expressions. The keyword INNER does not have to be specified. The database tables or views determined by tabref1 and tabref2 must be recognized by the ABAP Dictionary.
In a relational data structure, it is quite normal for data that belongs together to be split up across several tables to help the process of standardization (see relational databases). To regroup this information into a database query, you can link tables using the join command. This formulates conditions for the columns in the tables involved. The inner join contains all combinations of lines from the database table determined by tabref1 with lines from the table determined by tabref2, whose values together meet the logical condition (join condition) specified using ON>cond.
Inner join between table 1 and table 2, where column D in both tables in the join condition is set the same:
Table 1 Table 2
A
B
C
D
D
E
F
G
H
a1
b1
c1
1
1
e1
f1
g1
h1
a2
b2
c2
1
3
e2
f2
g2
h2
a3
b3
c3
2
4
e3
f3
g3
h3
a4
b4
c4
3
|--|||--|
Inner Join
A
B
C
D
D
E
F
G
H
a1
b1
c1
1
1
e1
f1
g1
h1
a2
b2
c2
1
1
e1
f1
g1
h1
a4
b4
c4
3
3
e2
f2
g2
h2
|--||||||||--|
Example
Output a list of all flights from Frankfurt to New York between September 10th and 20th, 2001 that are not sold out:
DATA: DATE LIKE SFLIGHT-FLDATE,
CARRID LIKE SFLIGHT-CARRID,
CONNID LIKE SFLIGHT-CONNID.
SELECT FCARRID FCONNID F~FLDATE
INTO (CARRID, CONNID, DATE)
FROM SFLIGHT AS F INNER JOIN SPFLI AS P
ON FCARRID = PCARRID AND
FCONNID = PCONNID
WHERE P~CITYFROM = 'FRANKFURT'
AND P~CITYTO = 'NEW YORK'
AND F~FLDATE BETWEEN '20010910' AND '20010920'
AND FSEATSOCC < FSEATSMAX.
WRITE: / DATE, CARRID, CONNID.
ENDSELECT.
If there are columns with the same name in both tables, you must distinguish between them by prefixing the field descriptor with the table name or a table alias.
Note
In order to determine the result of a SELECT command where the FROM clause contains a join, the database system first creates a temporary table containing the lines that meet the ON condition. The WHERE condition is then applied to the temporary table. It does not matter in an inner join whether the condition is in the ON or WHEREclause. The following example returns the same solution as the previous one.
Example
Output of a list of all flights from Frankfurt to New York between September 10th and 20th, 2001 that are not sold out:
DATA: DATE LIKE SFLIGHT-FLDATE,
CARRID LIKE SFLIGHT-CARRID,
CONNID LIKE SFLIGHT-CONNID.
SELECT FCARRID FCONNID F~FLDATE
INTO (CARRID, CONNID, DATE)
FROM SFLIGHT AS F INNER JOIN SPFLI AS P
ON FCARRID = PCARRID
WHERE FCONNID = PCONNID
AND P~CITYFROM = 'FRANKFURT'
AND P~CITYTO = 'NEW YORK'
AND F~FLDATE BETWEEN '20010910' AND '20010920'
AND FSEATSOCC < FSEATSMAX.
WRITE: / DATE, CARRID, CONNID.
ENDSELECT.
Note
Since not all of the database systems supported by SAP use the standard syntax for ON conditions, the syntax has been restricted. It only allows those joins that produce the same results on all of the supported database systems:
Only a table or view may appear to the right of the JOIN operator, not another join expression.
Only AND is possible in the ON condition as a logical operator.
Each comparison in the ON condition must contain a field from the right-hand table.
If an outer join occurs in the FROM clause, all the ON conditions must contain at least one "real" JOIN condition (a condition that contains a field from tabref1 amd a field from tabref2.
Note
In some cases, '*' may be specified in the SELECT clause, and an internal table or work area is entered into the INTO clause (instead of a list of fields). If so, the fields are written to the target area from left to right in the order in which the tables appear in the FROM clause, according to the structure of each table work area. There can then be gaps between table work areas if you use an Alignment Request. For this reason, you should define the target work area with reference to the types of the database tables, not simply by counting the total number of fields. For an example, see below:
Variant 3
... FROM tabref1 LEFT [OUTER] JOIN tabref2 ON cond
Effect
Selects the data from the transparent database tables and/or views specified in tabref1 and tabref2. tabref1 und tabref2 both have either the same form as in variant 1 or are themselves join expressions. The keyword OUTER can be omitted. The database tables or views specified in tabref1 and tabref2 must be recognized by the ABAP-Dictionary.
In order to determine the result of a SELECT command where the FROM clause contains a left outer join, the database system creates a temporary table containing the lines that meet the ON condition. The remaining fields from the left-hand table (tabref1) are then added to this table, and their corresponding fields from the right-hand table are filled with ZERO values. The system then applies the WHERE condition to the table.
Left outer join between table 1 and table 2 where column D in both tables set the join condition:
Table 1 Table 2
A
B
C
D
D
E
F
G
H
a1
b1
c1
1
1
e1
f1
g1
h1
a2
b2
c2
1
3
e2
f2
g2
h2
a3
b3
c3
2
4
e3
f3
g3
h3
a4
b4
c4
3
|--|||--|
Left Outer Join
A
B
C
D
D
E
F
G
H
a1
b1
c1
1
1
e1
f1
g1
h1
a2
b2
c2
1
1
e1
f1
g1
h1
a3
b3
c3
2
NULL
NULL
NULL
NULL
NULL
a4
b4
c4
3
3
e2
f2
g2
h2
|--||||||||--|
Example
Output a list of all custimers with their bookings for October 15th, 2001:
DATA: CUSTOMER TYPE SCUSTOM,
BOOKING TYPE SBOOK.
SELECT SCUSTOMNAME SCUSTOMPOSTCODE SCUSTOM~CITY
SBOOKFLDATE SBOOKCARRID SBOOKCONNID SBOOKBOOKID
INTO (CUSTOMER-NAME, CUSTOMER-POSTCODE, CUSTOMER-CITY,
BOOKING-FLDATE, BOOKING-CARRID, BOOKING-CONNID,
BOOKING-BOOKID)
FROM SCUSTOM LEFT OUTER JOIN SBOOK
ON SCUSTOMID = SBOOKCUSTOMID AND
SBOOK~FLDATE = '20011015'
ORDER BY SCUSTOMNAME SBOOKFLDATE.
WRITE: / CUSTOMER-NAME, CUSTOMER-POSTCODE, CUSTOMER-CITY,
BOOKING-FLDATE, BOOKING-CARRID, BOOKING-CONNID,
BOOKING-BOOKID.
ENDSELECT.
If there are columns with the same name in both tables, you must distinguish between them by prefixing the field descriptor with the table name or using an alias.
Note
For the resulting set of a SELECT command with a left outer join in the FROM clause, it is generally of crucial importance whether a logical condition is in the ON or WHERE condition. Since not all of the database systems supported by SAP themselves support the standard syntax and semantics of the left outer join, the syntax has been restricted to those cases that return the same solution in all database systems:
Only a table or view may come after the JOIN operator, not another join statement.
The only logical operator allowed in the ON condition is AND.
Each comparison in the ON condition must contain a field from the right-hand table.
Comparisons in the WHERE condition must not contain a field from the right-hand table.
The ON condition must contain at least one "real" JOIN condition (a condition in which a field from tabref1 as well as from tabref2 occurs).
Note
In some cases, '*' may be specivied as the field list in the SELECT clause, and an internal table or work area is entered in the INTO clause (instead of a list of fields). If so, the fields are written to the target area from left to right in the order in which the tables appear in the llen in der FROM clause, according to the structure of each table work area. There can be gaps between the table work areas if you use an Alignment Request. For this reason, you should define the target work area with reference to the types of the database tables, as in the following example (not simply by counting the total number of fields).
Example
Example of a JOIN with more than two tables: Select all flights from Frankfurt to New York between September 10th and 20th, 2001 where there are available places, and display the name of the airline.
DATA: BEGIN OF WA,
FLIGHT TYPE SFLIGHT,
PFLI TYPE SPFLI,
CARR TYPE SCARR,
END OF WA.
SELECT * INTO WA
FROM ( SFLIGHT AS F INNER JOIN SPFLI AS P
ON FCARRID = PCARRID AND
FCONNID = PCONNID )
INNER JOIN SCARR AS C
ON FCARRID = CCARRID
WHERE P~CITYFROM = 'FRANKFURT'
AND P~CITYTO = 'NEW YORK'
AND F~FLDATE BETWEEN '20010910' AND '20010920'
AND FSEATSOCC < FSEATSMAX.
WRITE: / WA-CARR-CARRNAME, WA-FLIGHT-FLDATE, WA-FLIGHT-CARRID,
WA-FLIGHT-CONNID.
ENDSELECT.
Kishore.

Similar Messages

  • Regarding Native SQL to access Oracle Data from SAP

    Dear Gurus,
    This query is regarding Native SQL.
    Our database is Oracle and the client's database is also Oracle.
    To access the data directly from the client's database(Oracle), can I use Native SQL commands?
    Is there any disadvantage to use Native SQL?
    If Native SQL can be used, can any one send me the code to access the data from Oracle?
    Points will be rewarded.
    Thanks & Regards,
    Neeraj K.

    The problem is always data integrity. Doing things this way you are bypassing any business logic. So for example if you are connecting to a SAP Oracle database. SAP will not support your SAP system as you are doing direct updates to the database. I would suppose that this would be the same for any other product using the Oracle database. If you are only reading data from the database then it should be fine. I would however always using API's to access/update data.
    Regards

  • 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

  • Regarding Native sql

    Hi guys,
    we are planning to go Oracle up next week. so could you please confirm below two points.
    1- we need to know what problem will occur if we used Native sql inside the Abap programs(due to Oracle up).
    2- Is it true that Native SQl communication passess thru Oracle client. Please confirm
    Thanks.
    Baasha

    Hi, please refer to the following pages.
    Native SQL
    Native SQL for Oracle
    especially in the first one, you will find your answers.
    Now, concerning point 2, have you considered posting the question in the SAP on Oracle forum in SDN ?
    Regards,
    Stéphan

  • Query Regarding Oracle SQL Developer

    Hi Guru's,
    There is a confusion regarding Installing SQL Developer, whether i need to install Oracle Software on my machine so that i use SQL Developer from my machine or i use SQL Developer without installing Oracle Software as i check the documentation for installing SQL Developer it gives info for installing SQL Developer JDK need to be installed and the correct path need to be initialized. May be this is stupid question but i want to clear my doubt.
    Any suggestion for the same. Thanks in advance.

    Hi,
    Install Oracle client Software first then SQL Developer
    Thanks,
    Ajay More
    http://www.moreajays.com

  • Query in native SQl

    I'm new to Native SQL commands.
    Can somebody tell me how to fine tune this code.
    Is there anything like FOR ALL ENTRIES in these commands also. We're using Oracle database.
    loop at it_cus1.
          EXEC SQL PERFORMING APPEND_IT_CUS2.
            SELECT SAP_MASTNR, ANK_MASTNR
            INTO
            :IT_CUS2-KUNNR, :IT_CUS2-DATLT
            FROM NOVARTIS.TABLE_ADRESS@ANKD
              WHERE ANK_MASTNR = :IT_CUS1-DATLT
          ENDEXEC.
    endloop.
    FORM append_it_cus2 .
      APPEND it_cus2.
      CLEAR it_cus2.
    ENDFORM.

    you could try cursor processing, it might be more efficient:
    EXEC SQL.
      OPEN C FOR
    SELECT SAP_MASTNR, ANK_MASTNR
    FROM NOVARTIS.TABLE_ADRESS@ANKD
    WHERE ANK_MASTNR = :IT_CUS1-DATLT
    ENDEXEC.
    loop at it_cus1.
      EXEC SQL.
        FETCH NEXT C into
        :IT_CUS2-KUNNR, :IT_CUS2-DATLT
      ENDEXEC.
      APPEND it_cus2.
      CLEAR it_cus2.
    ENDloop.
    EXEC SQL.
      CLOSE C
    ENDEXEC.

  • Regarding Native SQL and UNIX

    Hi guys. I've developed some programs using Native SQL to connect to a SQL Server database. To do so, i configured a connection on DBCO transaction. The develop SAP server runs on Windows platform, but QA and Production runs on UNIX. So, now i need to modify my programs to run on UNIX
    I know that in order to use DBCO conection to SQL Server requires the server to be on Windows, but i've been reading some postings and SAP notes, and i've read somewhere that you need at least ONE app server to be on windows...
    My question is this: is there a way to specify when connecting to DBCO to use a different app server? is this automatic?
    I hope i made miself clear...
    Jesus

    Solved it on my own

  • Query regarding Oracle SQL select statement

    Hi,
    How does Oracle ensures a consistent snapshot with the select statement
    without locking the table. My question is summarized with an example below:
    1. At time T1, Oracle select statement is fired and is fetching the result.
    2. At time T2, some DML operation is performed on the same table on which
    the select was executed and a commit was fired.
    3. At time T3, The Oracle select statement (Step 1) completes.
    My question is whether the records of transaction at time T2 will be visible at time T3 or not?
    If "not", then does it mean that Oracle retrieves the rows from the time of last commit.
    I would also like to know if for the above mechanism, Oracle would make use of the rollback segemt to access the rows at a particular instant of time.
    TIA
    Regards,
    Raj

    This is called Read Consistency in the oracle. Its all about SCN before starting the transaction.
    Lets say
    1. T1 executs SELECT statement on EMP table.
    2. T2 made an update on the EMP and commited.
    But, T1 only still sees only old image of the data not the new one. This is called read consistency.
    You will be having two images in the buffer, one is consistent and changed image.
    When the T1 give SELECT statement it notes the SCN of the transaction. Read oracle document about read consistency.
    SJH.

  • Executing Native SQL query for oracle

    Hi,
    I want to run following native sql query but it is giving me error ora:933,
    DATA: BEGIN OF WA,
          TSP_NAME(255) TYPE C,
          PER_USAGE(10) TYPE C,
          END OF WA.
    EXEC SQL PERFORMING loop_output.
    select t.tablespace_name,'(' || TO_CHAR(ROUND(100*(NVL(b.bytes,0)/NVL(a
    .bytes,0)))) || '%)' "TSUsed%" from dba_tablespaces t,
    ( select tablespace_name, sum(bytes)/1024/1024 bytes
    from dba_data_files group by tablespace_name) a,
    ( select e.tablespace_name, sum(e.bytes)/1024/1024 bytes
    from dba_extents e group by e.tablespace_name ) b,
    ( select f.tablespace_name, sum(f.bytes)/1024/1024 bytes
    from dba_free_space f group by f.tablespace_name ) c
    where t.tablespace_name = a.tablespace_name(+) and
    t.tablespace_name = b.tablespace_name(+) and
    t.tablespace_name = c.tablespace_name(+) into :wa.
    ENDEXEC.
    Please provide me the soln
    Regards,
    Bharat Mistry

    ORA-00933: SQL command not properly ended.
    Try:
    EXEC SQL PERFORMING loop_output.
    select
    into :wa
    ENDEXEC.
    (No "." at the end). If that doesn't work, try ending it with a ";"
    Rob

  • Performance of native sql query detoriates

    Dear Experts,
    The performance of my native SQL query is bad. On the database the query takes less than 5 seconds to process. From my abap program I get a session timeout dump after 10 minutes. What might be the possible reason.
    Warm Regards,
    Abdullah

    I am not a DBA, but this is a wild guess.
    I have a native SQL query. It was running fine all morning(transported it to production today). By afternoon the report was not giving any output.
    I went to the MS SQL query analyzer and executed the query, it returned the results in less than 5 seconds. The same query when I was executing from SAP using native SQL took more than 10 minutes and gave a dump(time exceeded).
    My database guy asked me to execute the following on the database. Dbcc dbreindex('tablename')
    The report is running fine since then. I am still not satisfied if this is the reason the performance is back on track, but yeah the report is running fine again. There seems to be some problem with the indexes.
    I am using standard classes provided by SAP to execute my query and after execution the resultset reference object is being closed, I am closing the connection.
    the code is as below.
          PERFORM:
            connect               USING con_name con_ref,
            select_into_table     USING con_ref,
            disconnect            USING con_ref.
    *  FORM connect
    *  Connects to the database specified by the logical connection name
    *  P_CON_NAME which is expected to be specified in table DBCON. In case
    *  of success the form returns in P_CON_REF a reference to a connection
    *  object of class CL_SQL_CONNECTION.
    *  --> P_CON_NAME  logical connection name
    *  <-- P_CON_REF   reference to a CL_SQL_CONNECTION object
    FORM connect  USING    p_con_name TYPE dbcon-con_name
                           p_con_ref  TYPE REF TO cl_sql_connection
                           RAISING cx_sql_exception.
    * if CON_NAME is not initial then try to open the connection, otherwise
    * create a connection object representing the default connection.
      IF p_con_name IS INITIAL.
        CREATE OBJECT p_con_ref.
      ELSE.
        p_con_ref = cl_sql_connection=>get_connection( p_con_name ).
      ENDIF.
    ENDFORM.                    " connect
    *  FORM select_into_table
    *  Selects some rows from the test table and fetches the result rows
    *  into an internal table whose row structure corresponds to the
    *  queries select list columns.
    FORM select_into_table
      USING   p_con_ref TYPE REF TO cl_sql_connection
      RAISING cx_sql_exception.
      DATA:
        l_stmt         TYPE string,
        l_stmt_ref     TYPE REF TO cl_sql_statement,
        l_dref         TYPE REF TO data,
        l_res_ref      TYPE REF TO cl_sql_result_set,
    *Data related query
        l_itab         TYPE TABLE OF t_pricing_report,
        l_row_cnt      TYPE i.
    * create the query string
    CONCATENATE
        'select A.SEQ,A.CONDTABLE,A.CONDNAME,A.VKORG,A.VTWEG,A.MATKL,A.MATNR,B.MTEXT,A.VKGRP,A.SGRPNAME,'
        'A.VKBUR,A.SOFFNAME,A.ZSALES,A.SCNTNAME,A.KUNNR,A.SCSTNAME,A.PRBATCH,A.INCO1,'
        'A.INCO2,A.DATAB,A.DATBI,A.KBETR,A.KONWA,A.KOSRT,B.MTART,B.GROES,B.VOLUM,B.EXTWG,B.WRKST,'
        'A.MXWRT,A.GKWRT,'
        'B.PATTERN,B.RIM,B.SERIES,B.SPDINDEX,B.LDINDX,B.MGROUP,B.APPLN,B.SDWALL,B.MGRPTXT'
        'FROM Z_PRICELIST A,Z_MATERIALVIEW B'
        'WHERE A.MANDT = ? AND'
              'B.MANDT = A.MANDT AND'
              'A.MATNR = B.MATNR AND'
              'A.KSCHL = ? AND'
              'A.CONDTABLE LIKE ? AND'
              'A.VKORG LIKE ? AND'
              'A.VTWEG LIKE ? AND'
              'A.MATKL >= ? AND A.MATKL <= ? AND'
              'A.MATNR >= ? AND A.MATNR <= ? AND'
              'A.INCO1 LIKE ? AND'
              'A.INCO2 LIKE ? AND'
              'A.ZSALES >= ? AND A.ZSALES <= ? AND'
              'A.KUNNR  >= ? AND A.KUNNR <= ? AND'
              'A.PRBATCH  >= ? AND A.PRBATCH <= ? AND'
              'A.VKBUR  >= ? AND A.VKBUR <= ? AND'
              'A.VKGRP  >= ? AND A.VKGRP <= ? AND'
              'B.WRKST  >= ? AND B.WRKST <= ? AND'
              'B.MTART  >= ? AND B.MTART <= ? AND'
              '? BETWEEN A.DATAB AND A.DATBI AND'
              'B.GROES LIKE ? AND'
              'B.LDINDX LIKE ? AND'
              'B.SPDINDEX LIKE ? AND'
              'B.RIM LIKE ? AND'
              'B.SERIES LIKE ? AND'
              'B.PATTERN LIKE ? AND'
              'B.MGROUP LIKE ?'
              'order by A.MATNR'
        INTO l_stmt SEPARATED BY space.                         "#EC NOTEXT
    * create a statement object
      l_stmt_ref = p_con_ref->create_statement( ).
    * bind input variables
      GET REFERENCE OF l_col1 INTO l_dref.
      l_stmt_ref->set_param( l_dref ).
    *binding other references here
      GET REFERENCE OF l_col33 INTO l_dref.
      l_stmt_ref->set_param( l_dref ).
    * set the input values and execute the query
      l_col1  = sy-mandt.
    *..Assigning values here
      l_col33 = p_mgroup.
    *  PERFORM trace_2 USING 'EXECUTE_QUERY' l_stmt l_col1 l_col2.
      l_res_ref = l_stmt_ref->execute_query( l_stmt ).
    * set output table
      GET REFERENCE OF l_itab INTO l_dref.
      l_res_ref->set_param_table( l_dref ).
    * get the complete result set
      l_row_cnt = l_res_ref->next_package( ).
    * display the contents of the output table
    *  PERFORM trace_next_package USING l_itab.
    *  PERFORM trace_result USING l_row_cnt 'rows fetched'.
      pricing_report[] = l_itab[].
      free l_itab.
    * don't forget to close the result set object in order to free
    * resources on the database
      l_res_ref->close( ).
    ENDFORM.                    "select_into_table
    *  FORM disconnect
    *  Disconnect from the given connection. In case of the default
    *  connection this can be omitted.
    FORM disconnect
      USING   p_con_ref TYPE REF TO cl_sql_connection
      RAISING cx_sql_exception.
      DATA: l_con_name TYPE dbcon-con_name.
      l_con_name = p_con_ref->get_con_name( ).
      CHECK l_con_name <> cl_sql_connection=>c_default_connection.
    *  PERFORM trace_0 USING 'CLOSE CONNECTION' l_con_name.
      p_con_ref->close( ).
    *  PERFORM trace_result USING l_con_name 'closed'.
    ENDFORM.                    "disconnect
    *  FORM handle_sql_exception
    *  Write appropriate error messages when a SQL exception has occured
    *  -->  P_SQLERR_REF  reference to a CX_SQL_EXCEPTION object
    FORM handle_sql_exception
      USING p_sqlerr_ref TYPE REF TO cx_sql_exception.
      FORMAT COLOR COL_NEGATIVE.
      IF p_sqlerr_ref->db_error = 'X'.
        WRITE: / 'SQL error occured:', p_sqlerr_ref->sql_code,
               / p_sqlerr_ref->sql_message.                     "#EC NOTEXT
      ELSE.
        WRITE:
          / 'Error from DBI (details in dev-trace):',
            p_sqlerr_ref->internal_error.                       "#EC NOTEXT
      ENDIF.
    ENDFORM.                    "handle_sql_exception

  • Query SAP Database with Native Sql.

    Hi,
    I would like to query the table MARA with native sql and return all headings and data
    Select * from MARA where MATNR = '00000000151515'          
    <i>I need this to be able to TEST my Sql statements.</i>
    In SqlServer you have the Query Analyser where I can do just this, but is there some nice in SAP Tool for this as well ?
    [Unfortanely I can't connect to SAP_U01 database from QA...]
    //Martin

    Hi Martin,
    maybe you give ST05 a try: last button gives the possibility to enter a SQL-statement directly - and for explanation it has to be executed (somehow).
    Regards,
    Christian

  • Mapping Problem with Native SQL query

    My application uses a native SQL query to locate certain entities. It looks like this:
    SELECT UPLOADATTEMPTREF, STUDENTNUMBER, USERID, WORKITEMCODE, WORKITEMINSTURN, WORKITEMTITLE, MODULERUNCODE, STUDENTNAME, SUBMISSIONDEADLINE, UPLOADATTEMPTSERVERDATE, FILENAME, UPLOADCOMPLETESERVERDATE, NEWFILENAME, FILESIZE, FILEPATH, DOWNLOADSERVERDATE, MODULECODE, MODULETITLE
    FROM Submission_Attempt WHERE UPLOADATTEMPTREF IN (
    SELECT uploadAttemptRef FROM (" +<br /><br />                         "SELECT MAX(uploadAttemptRef) AS uploadAttemptRef, UserID, workItemInstUrn, " +<br /><br />                         "workItemCode FROM Submission_Attempt where workiteminsturn = ?1 " +<br /><br />                         "GROUP BY UserID, workItemInstUrn, workItemCode) Table1 ) " +<br /><br />                         "and uploadCompleteServerDate is not null;"<br />
    My expectation was that EclipseLink would be able to handle the mapping of the results to the entity quite happily. However, I get a NonSynchronizedVector of Objects - each Object representing one field of data.
    I need help with either:
    Converting the above SQL into JPQL so that I (hopefully) don't have to worry about the SQL or
    Understanding why this isn't working properly...
    Anyone able to help?
    Edited by: phunnimonkey on Nov 6, 2008 3:33 AM

    Never mind - the problem was to do with not specifying a class when creating the native query.

  • Native sql query in sap

    Hi all,
    my open SQL query is like
    select matnr  matkl from mara into corresponding fields of table i_mara for all entries in i_marc
         where matnr = marc-matnr.
    can u plz tell me the native sql for the same query?
    Thanks.
    pabi

    hi,
    EXEC SQL PERFORMING form.
    Native SQL Anweisung
    ENDEXEC.
    EXEC SQL
    select matnr matkl from mara into corresponding fields of table i_mara for all entries in i_marc
    where matnr = marc-matnr.
    ENDEXEC.
    For further ref pls refer to link...
    Re: Normal SQL Query othern than Native
    Native SQL

  • Fetch join with Native SQL Query?

    Hello all,
    I am using the J2EE 5.0 persistence api with the SUN appserver v9. As the java persistence api does not yet support spatial queries ("... where contains(polygon, point)") I have to use native SQL queries for that purpose.
    Now my question is how can I "join fetch" my ManyToOne-related entities when using a native SQL query? Is this somehow possible using the SqlResultSetMapping annotation?

    Never mind - the problem was to do with not specifying a class when creating the native query.

  • Native SQL query - Need help

    Hi All,
    We have a native SQL query accessing Oracle database(given below).
    Can anyone please let me know what this query is about and how can we fine tune the query?
    SELECT O.OBJECT_NAME ,
                   H.SID,
                   HS.MACHINE,
                   HS.PROCESS,
                   W.SID,
                   WS.MACHINE,
                   WS.PROCESS,
                   H.CTIME,
                   W.CTIME,
                   WS.ROW_WAIT_OBJ#,
                   WS.ROW_WAIT_FILE#,
                   WS.ROW_WAIT_BLOCK#,
                   WS.ROW_WAIT_ROW#,
                   HP.SPID,
                   WP.SPID
            FROM V$LOCK H, V$LOCK W, V$LOCK I, V$LOCK I2, ALL_OBJECTS O,
                 V$SESSION HS, V$SESSION WS, V$PROCESS HP, V$PROCESS WP
            WHERE   H.ID1 = W.ID1
            AND     H.SID <> W.SID
            AND     H.TYPE IN ('TX','DL')
            AND     H.REQUEST = 0
            AND     H.SID = I.SID
            AND     I.TYPE = 'TM'
            AND     I.ID1 = O.OBJECT_ID
            AND     I.ID1 = I2.ID1
            AND     W.SID = I2.SID
            AND     I2.TYPE = 'TM'
            AND     H.SID = HS.SID
            AND     W.SID = WS.SID
            AND     HS.PADDR = HP.ADDR
            AND     WS.PADDR = WP.ADDR
            INTO :EXCL_LOCK_WAITERS-OBJ_NAME   ,
                 :EXCL_LOCK_WAITERS-HOLDER_SID ,
                 :EXCL_LOCK_WAITERS-H_HOSTNAME ,
                :EXCL_LOCK_WAITERS-HOLDER_PID ,
                 :HOLDER_PID ,
                 :EXCL_LOCK_WAITERS-WAITER_SID ,
                 :EXCL_LOCK_WAITERS-W_HOSTNAME ,
                :EXCL_LOCK_WAITERS-WAITER_PID ,
                 :WAITER_PID ,
                 :EXCL_LOCK_WAITERS-HELD_SINCE ,
                 :EXCL_LOCK_WAITERS-WAITSSINCE,
                 :ROW_WAIT_OBJ,
                 :ROW_WAIT_FILE,
                 :ROW_WAIT_BLOCK,
                 :ROW_WAIT_ROW,
                 :H_PROCESS,
                 :W_PROCESS
          ENDEXEC
    Thanks in advance.
    Neethu Mohan

    Hi Neethu,
    It gives you an overwiew of blocking Oracle sessions.
    1. In general, the SQL checks Oracle sessions (SID's) that were requirering a DML lock ('TM') and now holding row locks (TX)  to prevent destructive interference of simultaneous conflicting DML or DDL operations. DML statements automatically acquire both table-level locks and row-level locks ('TX')  => holders
    It joins these with the sessions that are waiting of releasing the lock by the holders  => waiters.
    2. it retrieves the detail information wich  Oracle process , the object (table) , it's row , block  and file
    are affected by the locks.
    3. Normally, the locks are only hold for a short period of time. If you have blocking sessions it may be of a log running task (i.e. mass data update of a table) ; but it could also be a application bug due to improper handling of concurrent updates of the same object.
    4. Tuning
    V$tables are expensive to query: Why?
    v$ tables are generally Oracle memory structures.
    v$ tables are not read consistent.
    v$ tables require latches to access -- cannot modify and read memory at the same
    time.
    heavy access to v$ tables like this may cause some serious heavy duty contention.
    Especially if you self join V$lock several times.
    So the best would be to save the contents of V$LOCK in some table:
    Create table mylocks as select * from v$lock;
    Use that table for self-joining and joins to the other tables.
    You can also CTAS the other v$ tables to bypass the performance bottleneck while retrieving
    v$ directly.
    You can empty or drop the created tables any time for new data.
    Because you want to investigate only lock hold for a longert time  to copy the v$ memory structures into
    physical tables is not a disadvantage. You certainly will wait longer on finishing your query
    instead of copy them into the tables.
    Hope this helped
    yk

Maybe you are looking for