Native SQL in ABAP

I need a query or stored procedure to get data from a table name specified by a variable (here 'TableName').
The stored procedure would be called everytime with a parameter that specifies the tablename to be queried.
The following piece of code works in Oracle, but when I use it in ABAP it gives a 'Table Access Error'.
DECLARE @Query varchar(300), @TableName varchar(30)
SET @TableName = 'Tab1'
SET @Query = 'SELECT * FROM ' + @TableName
EXEC (@Query)
Please help me out.

Hello again,
Sorry for the misunderstanding!!
Have you tried to concatenate the table??
I mean to concatenate the values as a string??
I have never done it before, but it could work. Try to write it like a dynamic select:
column_syntax = `car name plate`.
dbtab_syntax = `zcars_names`.
SELECT (column_syntax)
       FROM (dbtab_syntax)
       INTO CORRESPONDING FIELDS OF TABLE itab.
try to concatenate or assign a value on a string variable.
myvar = 'tab1'
SET @TableName = myvar
Will it work, i dont know?? Try it!!...
Be careful with the quotation marks...you know how SQL make us crazy with it!!
Gabriel
Message was edited by: Gabriel Fernando Pulido V.

Similar Messages

  • Reading BLOB in Native SQL from ABAP program

    Hello,
    I'm trying to read content of a BLOB field from a table with Native SQL in ABAP like this:
    DATA: l_bytes type xstring.
    EXEC SQL.
      SELECT bytes INTO :l_bytes FROM tablename
    ENDEXEC.
    But when I'm using xstring it returns only 32768 bytes. When using type x length 65000 for l_bytes it returns 65000 bytes, but x is limited to 65535 bytes only. So why it returns only 32768 bytes in direct sql? For DB2 I found note 610342 where you need to add \lob to the statement, I tried with Oracle but doesn't work.
    DATA: CLOB_VAR TYPE STRING.
    DATA: BLOB_VAR TYPE XSTRING.
    EXEC SQL.     
      SELECT FCLOB, FBLOB FROM ZZTAB        INTO :CLOB_VAR\lob, :BLOB_VAR\lob
    ENDEXEC.
    Regards
    Markus

    Hi Markus,
    you have to read it in chunks (remember a blob could be up to 4 Gbyte!).
    I assume you store the byte stream in the field (no bfile pointer to a file ).
    Give you a pseudocode that you get the picture.
    Would recommend that you read the Oracle manual (db Version?)
    9i
    http://download.oracle.com/docs/cd/B10501_01/appdev.920/a96612/d_lob2.htm#1008611
    10g
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#ARPLS600
    chunksize = 32768 .  " or use 65000 . This is the amount of the blob part you want to read
    offset = 1.
    *get the row of interest and retrieve blob's length
    Exec sql.
    select  dbms_lob.getlength(your_blob)  :blob_length from blob_table where my_primary_key = 1
    end exec.
    *calculate times to read from blob  until the end (well, leave the adjustment to you
    * in case of an uneven  fraction)
    ntimes = blob_length / chunksize .
    Do ntimes
    *loop and get the chunks into your variable:
    * start reading from offset chunksize of bytes
    exec sql.
    select dbms_lob.substr(your_blob, :chunksize,:offset) into  :xblobvar  from blob_table
    where my_primary_key = 1
    endexec.
    *don't know what you want to do with the blob chunk...
    *process  :xblobvar
    offset = chunksize * ntimes .
    enddo.
    bye
    yk

  • Are there any risks to use native sql in ABAP to access external DB

    here is a requirement to use native sql in abap program to access external DB to load some data into sap. Are there any risks and effects which SAP not recommend ?
    Can anybody show some official document to me because I want to know some risks and dangerous to report to my manager..thanks very much.

    hi Anversha s 
    thank you for your reply
    I means what's the risk when to use native sql to access external DB..
    can you show me some examples about open sql which is used to access external DB...
    Now I am investigating the technique about the connection
    between SAP (by abap program) and external DB...the supporter suggestion is to use native sql to access external DBs.but my manager is afraid of the risks when to use native sql,So I have to report the effective document (example: SAP official document) to explain  to my manager.
    thanks very much

  • Using Native SQL in ABAP for DB2 database

    Dear Friends,
           I have 500K records in ITAB(Internal table) which needs to insert in 'Z' transparent table. Currently it is taking hours of time for insertion and commit. 
    Does using Native SQL helps in performance or any suggestions? If so please send the code. Our database is DB2.
    Your immediate reply is appreciated. Thanks in advance.

    Hi Rama,
    Using array inserts and commit after each Insert, set up your array size as a parameter and try  different array sizes.
    I would start with 2000 and increment by 1000 or 2000 and see what the optimal array size is.
    I would think more commits are desirable, as the array gets bigger it takes longer for the system to prepare in the event of a rollback.
    Just remember to commit after each insert. And are you enqueueing the table first?
    Hope this helps.
    Filler

  • Native SQL from ABAP - ORA 02396 max idle time exceeded

    Hello,
      I am trying to read a table outside of the R/3 environment using native SQL statements. I'm getting the data just fine. But every other time (depending on elapsed time), I get the ORA-02396 exceeded maximum idle time, connect again. Here's the SQL code I'm using and I'm obviously not getting disconnected but I'm not sure why. Any help?
    Open a native SQL connection.
      EXEC SQL.
        connect to 'ONECD'
      ENDEXEC.
    Retrieve information from the BVER tables.
      EXEC SQL PERFORMING read_dental.
        select emp_ssn_num, emp_fname, emp_lname,
               to_char(start_date, 'YYYYMMDD') as start_date,
               rec_type,
               to_char(eff_date, 'YYYYMMDD') as eff_date,
               vendor_plan_id
            into :dental
            from opr$8oc.BVER_CURR_DENTAL_MASTER
      ENDEXEC.
      EXEC SQL PERFORMING read_medical.
        select emp_ssn_num, emp_fname, emp_lname, rec_type,
               to_char(start_date, 'YYYYMMDD') as start_date,
               to_char(eff_date, 'YYYYMMDD') as eff_date,
               network_code, pcp_number, patient_flag,
               vendor_plan_id,
               to_char(network_eff_date, 'YYYYMMDD') as
                       network_eff_date,
               to_char(pha_eff_date, 'YYYYMMDD') as
                       pha_eff_date
             into :medical
             from opr$8oc.BVER_CURR_MEDICAL_MASTER
      ENDEXEC.
    Disconnect from the native SQL connection.
      EXEC SQL.
        DISCONNECT 'ONECD'
      ENDEXEC.
    The system log has messages like 'Work process is in reconnect status' and 'Work process has left reconnect status' after the ORA-02396 message. And I specifically do a disconnect at the end and a connect at the beginning, but it looks like it is trying to do a reconnect?
    Thanks,
    Diane

    Hi Daine,
    Oracle Parameter IDLE_TIME set by the administrator.
    1. Since you are using Secondary database
       connection, the connection must
       have been made with the help of BASIS Team.
    2. This secondary database ORACLE
       has some settings/parameters
       which have been set to say 10 minutes, 60 minutes etc.
       , so what happens,
       if there is NO ACTIVITY / NO SQL / NO INTERACTION
       with the database ,
       the connection is IDLE
       and hence ORACLE then disconnects by itself.
    3. Contact your basis team / oracle administarotr
      team to INCREASE this setting.
      (they do it for some security purpose, firewall etc)
    I hope it helps.  
    Regards,
    Amit M.
    Message was edited by: Amit Mittal

  • Accessinng Table using Native SQL in ABAP Program

    Hi Experts,
    I need to access a table that is created in Oracle.
    But while writing a select query as below:
      EXEC sql.
       SELECT MAX(ID_EVENTO)
         INTO :LV_ID_EVENTO
         FROM ZTAB.
      ENDEXEC.
    I am getting a dump saying "ZTAB doesnot exist" or IF I use ZTAB@ifsap then it dumps saying "Database name is missing a component".
    Do I need to add some suffix to the table name like @ifsap to ZTAB?
    Also, can I use SY-SUBRC to check to the success and failure for SELECTION OR INSERTION Operation?
    Thanks
    Depesh

    Hello,
    Try using SAP<SID>.ZTAB in your query.
    For example SAPC05.ZTAB
    Regards,
    Yoganand.V

  • Possible to do "grant" sql statement in Native SQL?

    We have a need to do a grant of access from one of our systems out for various applications.  In order for this to work we need to run a grant access command on the table and are trying to put a wrapper around this so we can use an abap.  Below is the code I am unit testing.  Two questions.  First, can a grant be done via native SQL in abap?  Second, if it can be done, what is the error with the logic where I am trying to put in the table name via a parameter.
    REPORT  ZLJTEST2.
    tables dd02l.
    DATA scarr_carrid TYPE dd02l-tabname.
    SELECT-OPTIONS s_carrid for dd02l-tabname no intervals.
    DATA s_carrid_wa LIKE LINE OF s_carrid.
    DATA name TYPE c LENGTH 20.
    TRY.
        EXEC SQL.
          CREATE FUNCTION selfunc( input CHAR(20) )
            RETURNING char(20);
            DEFINE output char(20);
            set schema sapr3;
            grant select on table input to group infouser;
            RETURN output;
            END FUNCTION;
        ENDEXEC.
        LOOP AT s_carrid INTO s_carrid_wa
                         WHERE sign = 'I' AND option = 'EQ'.
          TRY.
             EXEC SQL.
                EXECUTE PROCEDURE selfunc( IN  :s_carrid_wa-low,
                                           OUT :name )
              ENDEXEC.
              WRITE: / s_carrid_wa-low, name.
            CATCH cx_sy_native_sql_error.
              MESSAGE `Error in procedure execution` TYPE 'I'.
          ENDTRY.
        ENDLOOP.
        EXEC SQL.
          DROP FUNCTION selfunc;
        ENDEXEC.
      CATCH cx_sy_native_sql_error.
        MESSAGE `Error in procedure handling` TYPE 'I'.
    ENDTRY.

    Hi,
    Yes it is posible.
    I made one program like you want. But it need very long code.
    Here I explain the idea:
    1. Create Screen with input TEXT EDIT CONTROL.
        This is for input SQL Statement.
    2. Get SQL Statement from Text Edit Control using method <b>get_text_as_r3table</b>.
    3. Now we need to separate SQL Statement into different table.
        We Separate SELECT, FROM, WHERE, GROUP, HAVING, ORDER, etc.
    4. We need dynamic internal table to store the data.
    5. Select the data according SQL statement.
          SELECT (IT_SELECT)
            into corresponding fields of table  <dyn_table>
          FROM (IT_FROM)
          WHERE (IT_WHERE)
          GROUP BY (IT_GROUP)
          HAVING (IT_HAVING)
          ORDER BY (IT_ORDER).
    6. Display our data using ALV GRID
    Hopefully it will help you.
    Regards,

  • Performance issue using Native SQL

    Hi
        I am getting the data from Oracle database using Native SQL in ABAP. I am facing performance problem when i am using Native SQL to get data from Oracle database.Its been very slow and getting timed out.
    This is the code i am using for this.
    EXEC SQL PERFORMING BUILD_TAB.
    Get the territory id
        SELECT TERR_ID
          FROM DWPROD.VW_ARDETAIL_PRD1@DWP
          INTO :IT_TERR-TERR_ID
               :DG_TERR_ID
         WHERE COMPANY     = :dt_output-bukrs
           AND PAY_ADDR_ID = :dt_output-kunnr
           AND DOC_NO      = :dt_output-belnr
           AND DOC_ITEM_NO = :dt_output-buzei
      ENDEXEC.
      IF sy-dbcnt >= 1.
        READ TABLE it_terr INDEX 1.
        dg_terr_id = it_terr-terr_id.
        EXEC SQL.
    Get the Saled rep id, name
          SELECT MR_USER_ID,
                 MR_NAME
            FROM DWPROD.VW_TERR@DWP
            INTO :dt_output-srep_id,
                 :dt_output-srep_name
           WHERE TERR_ID = :DG_TERR_ID
        ENDEXEC.
    *Get sales manager id and sales manager name
        EXEC SQL.
          SELECT SALES_GRP_ID
            FROM DWPROD.VW_TERRRPT@DWP
            INTO :DG_SGRPID
           WHERE TERR_ID = :DG_TERR_ID
        ENDEXEC.
        IF sy-dbcnt >= 1.
          EXEC SQL.
            SELECT MGR_USER_ID,
                   MGR_NAME
              FROM DWPROD.VW_SGRP@DWP
              INTO :dt_output-sman_id,
                   :dt_output-sman_name
             WHERE SALES_GRP_ID = :DG_SGRPID
          ENDEXEC.
        ENDIF.
      ENDIF.
    Can any one suggest a solution to improve the performance.
    Thnaks
    Vianney

    Hi John!
    Looks like you need just one entry out of the tables, but you select 'into table'.
    Try to add a 'up to 1 rows' restriction, then Oracle will be much faster with the execution.
    To get an idea, who this parameter looks like in native SQL for Oracle, write a simple test program with an open SQL statement (including this parameter / select single) and run a SQL-trace (ST05). Here you can see in 'explain' how native translation looks like, can also maintain some small tests with 'enter SQL statement'.
    Regards,
    Christian

  • CREATE VIEW in ABAP (Open SQL or Native SQL)

    Hi all you experts!
    I want to create a VIEW in ABAP. I have created Table Views using ABAP Dictionary (in transaction SE11), I don't have any problem with them.
    But, what I need is to create a dynamic view, I mean, a view that can be created/replaced (or modified) at runtime. Is this possible with SAP Open SQL, I don't think so... that is why I tried to created using native SQL but it is not working.
    Here is the code:
      EXEC SQL.
        CREATE VIEW [ZMXRFIV_GLPCA]
          AS SELECT
             T1.GL_SIRID,
             T1.POPER,
             T1.RBUKRS,
             T1.RPRCTR,
             T1.RACCT,
             T1.HSL
          FROM
             GLPCA T1
          INNER JOIN
             SKA1 T2
          ON
             T1.RACCT = T2.SAKNR
          WHERE
            T1.RVERS      =  '000'
            AND T1.RYEAR  =  '2008'
            AND T1.KOKRS  =  'PI01'
            AND T2.KTOPL  =  'PI00'
            AND T2.XBILK  <> 'X'.
      ENDEXEC.
    I have tried using quotes (") for the view name, parenthesis and even using only the name but this make no difference.
    Do any of you experts have any idea?
    PS: After creating the view I need to do a SELECT INTO TABLE to that view and finally delete this view and continue working with the data on the internal table.

    Hi ,
    oh yes it is an object (well, how the database should handle it in any context if it wasn't)
    i.e. for ORACLE you would have several thousands of them:
    select count(*) from dba_objects where object_type ='VIEW'
    If you avoid some kind of foreground processing (i.e. pull the data over the network) and handle the processing inside the database it can improve somehow performance a little (i.e. using the retieved rows of the view to stuff into a database table directly). But his may not always possible...
    bye
    yk

  • Using Native SQL in Web Dynpro for ABAP

    Hi folks,
    I am trying to access an oracle database in web dynpro for ABAP via Native SQL.
    I am able to read row by row from the database into a work area, but I am unable to read the whole table from the database into an internal table.
    Please advise as to how I can do this, and thanks for reading.
    PS: Thomas, I wasn't off-topic on the previous thread; I forgot to mention that I was trying to do this under Web Dynpro for ABAP.

    Hello,
    it doesn't matter if you try this with Web Dynpro ABAP, BSP or any other framework, this is a general ABAP question and not related to this forum.
    Regards,
    Rainer

  • Need Help : Native SQL ABAP dump "DBIF_DSQL2_SQL_ERROR" on procedure "APS_ORDER_CHANGE".

    Hi All,
    We are facing an issue and want to check if you have seen it in past and can help us in resolving it. Any input will be greatly appreciated.
    Issue:
    While executing product heuristic on few product/location combinations in product view, we encounter native SQL ABAP dump “DBIF_DSQL2_SQL_ERROR” on
    procedure “APS_ORDER_CHANGE”.
    We were debugging for one particular product/location combination, this combination has 2 planned orders, and the Internal order number of these planned orders are
    given as input to this procedure “APS_ORDER_CHANGE”. These 2 internal order numbers are the only inputs given to this procedure.
    When we try to delete those planned orders we again encounter same ABAP dump. There are many product/location having the same issue.
    We also checked variable duration maintained on the PPM of this product/location, and was fine.
    For more deatils : Please check the attached document of downloaded ABAP Dump.
    Thanks and Regards,
    Pritesh Jain

    Hi Pritesh.
    What liveCache version/build/patch are you on? What is the database error text shown in this dump?
    If it is exactly the one below
    Database error text........: "POS(1) Work rolled back: tExcept 30730 in
    APS_ORDER_CHAN"
    You can try running report SLCA_EMERGENCY_SWITCH, then turning off the option "Verify that all input table records have been read" and saving the results. If that solves the issue, you can use this as a workaround until the next time you upgrade your liveCache build.
    To get a clear root cause, you may need to create an OSS incident under BC-DB-LCA component providing a reproducible example.
    Regards,
    Tiago

  • Who to use Native SQL statements in ABAP

    hi all,
    who to use native sql staements in abap bypassing Application server.
    with regards,
    suresh babu aluri.

    Hi
    Native SQL statements define an area in an ABAP program in which one or more Native SQL statements are to be carried out. The area between EXEC and ENDEXEC is not completely checked by the syntax check. The statements entered there are passed to the Native SQL interface and processed there as follows:
    Almost all SQL statements that are valid for the addressed database system can be included between EXEC and ENDEXEC, in particular the DDL statements. These SQL statements are passed from the Native SQL interface to the database system largely unchanged. The syntax rules are specified by the database system, in particular the case sensitivity rules for database objects. If the syntax allows a separator character between individual statements, you can include several Native SQL statements between EXEC and ENDEXEC. Generally, the semicolon ( is used as the separator character.
    You can also include SAP-specific Native SQL language elements between EXEC and ENDEXEC. These statements are not passed directly from the Native SQL interface to the database, but are converted appropriately.
    All Native SQL statements bypass SAP buffering.
    The ENDEXEC statement sets sy-dbcnt to the number of table rows processed in the last Native SQL statement. After implicit cursor processing with PERFORMING, sy-dbcnt contains the total number of lines read.
    Programs with Native SQL statements are generally dependent on the database system used, so that they cannot be executed in all ABAP systems. This is especially true for the examples in this section, which was written for Informix database systems.
    Example
    Inserting two rows in the database table SCARR. If neither of these rows exists, sy-subrc is set to 0 by ENDEXEC and sy-dbcnt to 1. Otherwise, an exception is raised and handled.
    DATA: exc_ref    TYPE REF TO cx_sy_native_sql_error,
          error_text TYPE string.
    TRY.
        EXEC SQL.
          INSERT INTO scarr
                      (MANDT, CARRID, CARRNAME, CURRCODE, URL)
            VALUES ('000', 'FF', 'Funny Flyers', 'EUR',
                    'http://www.ff.com');
          INSERT INTO scarr
                     (MANDT, CARRID, CARRNAME, CURRCODE, URL)
            VALUES ('000', 'EF', 'Easy Flyers', 'EUR',
                    'http://www.ef.com');
        ENDEXEC.
      CATCH cx_sy_native_sql_error INTO exc_ref.
        error_text = exc_ref->get_text( ).
        MESSAGE error_text TYPE 'I'.
    ENDTRY.
    Reward points if useful
    Regards
    Anji

  • Passing data from abap-program to mssql database table thro native sql

    Hi,
    To pass the data from abap-program to mssql server,i have created database connection through dbco t.code.
    now i am trying to get connection thro native sql but am not able to get it .Am working in ECC 5.0.
    Could anyone help me on this.Did i miss anything?
    i have tried Native-sql like this.
    DATA: CON_NAME LIKE DBCON-CON_NAME VALUE 'BIW'.
    EXEC SQL.
      CONNECT TO :con_name AS 'C1'
    ENDEXEC.
    Thanks in advance.

    Hi,
    Trying to do the same here, only using Oracle DB.
    DATA:     dbc TYPE DBCON_NAME VALUE 'BI'
    TRY.
      EXEC SQL.
        CONNECT TO :dbc
      ENDEXEC.
      IF sy-subrc NE 0.
        RAISE EXCEPTION TYPE cx_sy_native_sql_error.
      ENDIF.
    CATCH cx_sy_native_sql_error INTO oref_native_sql_error.
      sql_emsg = oref_native_sql_error->get_text( ).
      MESSAGE sql_emsg TYPE 'I'.
    ENDTRY.
    I keep getting the message 'Native SQL exception has occured' (because of the RAISE statement, I wonder how we can get a meaningfull error description).
    Of course this can be a result of a number of network issues, so I'm trying to resolve this together with my BC admin.
    I suggest the same to you..
    In the meantime, if anyone can help out, it will be appreciated.
    Regards,
    SD

  • ABAP native SQL

    Guys,
    Did anyone know how Oracle synonym works with ABAP native SQL?
    I have a database in oracle with a predefined synonym already used in ABAP code.
    Now i want to change the current synonym to point towards a new database in oracle, my doubt is, are these synonyms point to the oracle table level or they point to the entire database?
    Regards,
    Sudeep

    hi ,
    If your are pointing to New database  , Please check whether   synonyms  for those tables   are there  in the new Oracle  database  .
    You need  to maintain Entry of Database Connection  in  : DBCON table 
    There migth be OLD DB connection in  DBCON table   ,so need to create  for new database connection   or Change
    Accordingly  .
    Synonyms are Generally Pointers which allow access  for object which resides somewhere else  .
    TCode DBCO is used to create a DBCON connection.  
    Regards
    Deepak.

  • SELECT ROWID using ABAP without Native SQL ?

    Hi All,
    is that possible to query Oracle ROWID from ABAP without using Native SQL ? Please advise.
    Thank You and Best Regards
    FL

    Since this is usually not relevant for application programming and also database specific, I'm fairly sure this information hidden by the DBI and you cannot access it via Open SQL, so native SQL seems to be your only choice.
    Thomas

Maybe you are looking for

  • Closed Quotes, single and double, are unavailable

    Does anyone have any recent issues with InDesign document not automatically inserting either a closed single or closed double quote? I have not experienced this before, and I've checked pref>type with no current doc open, I've checked multiple font j

  • Purchase documents

    While creating purchase documents (PO,PR), system says "acc. assignment mandatory for this material.Enter acc.assignment category" Message no. ME062 Diagnosis:There is no provision for value-based inventory management for this material type in this p

  • Edit Distribution List in Address Book is gray

    After updating to Lion OS 10.7, the Edit Distribution List menu selection is grayed out. How do we edit Distribution List (Groups) with contacts with multiple email addresses?

  • Lots of unsolicited weird music appearing in music library

    This is really strange. I purchased a new computer (HP). Loaded the most recent version of iTunes. Plugged in my iPod Touch. When I later placed the iPod in to play in the house Bose speaker, it had, get this, about 500 new songs. Bizarre. Like full

  • Problem at save card to pdf in Photo

    Hi all! Please help me to solve this problem, I created a card in iphoto 11 (please check my image as below) then I chose print/ save as pdf but pdf file is completely different than the one I created in iphoto. I don't know how to print out the card