如何执行存储在变量中的OpenSQL查询?

时间:2017-07-11 13:43:51

标签: sap abap opensql

 DATA: QUERY TYPE STRING,
  Q2 TYPE STRING,
  MAINQUERY TYPE STRING.
 QUERY = 'SELECT MARA~MATNR MARA~MBRSH MARA~MTART MARA~ERSDA MARA~PACKCODE FROM MARA INTO TABLE ITAB'.

Q2 = 'WHERE MARA~MBRSH = IDNAME.'.
CONCATENATE QUERY Q2 INTO MAINQUERY.
WRITE: /3 MAINQUERY.
MAINQUERY.

是否可以在变量和执行中存储连接的选择查询?是否有任何关键字在变量中运行字符串abap ??

2 个答案:

答案 0 :(得分:0)

是的,可以使用via cl_sql_statement类进行本机sql注入,您可以查看Internet上的文档。但是,你应该小心,因为本机sql注入可能是危险的。您可以查看演示程序ADBC_DEMO

  DATA: con_ref    TYPE REF TO cl_sql_connection,
    l_sqlerr_ref TYPE REF TO cx_sql_exception.
  DATA:
  l_stmt     TYPE string,
  l_stmt_ref TYPE REF TO cl_sql_statement.

  CREATE OBJECT con_ref.
  con_ref = cl_sql_connection=>get_connection( ).
  " create a statement object
  l_stmt_ref = con_ref->create_statement( ).

  "Create query
  CONCATENATE
   'insert into' p_tabsim 'select * from' p_tabreal
  INTO l_stmt SEPARATED BY space.
  TRY .
     l_stmt_ref->execute_update( l_stmt ).

  CATCH cx_sql_exception INTO l_sqlerr_ref.
    MESSAGE 'Problem' TYPE 'W'.
  *    RAISE EXCEPTION l_sqlerr_ref.
  ENDTRY.
  con_ref->commit( ).
  con_ref->close( ).

还有另一种方法,即动态选择查询创建,但您必须键入“select”关键字。 Here是一些有用的信息。

答案 1 :(得分:0)

基于Oguz提案的解决方案:

private final String QUERY_FETCH_ALL_RECORD = "SELECT * from employeeRecord";

您应该仔细修改SQL查询,因为本机SQL高度依赖于DB-backend。例如,查询中的 TYPES: BEGIN OF ty_result, matnr TYPE mara-matnr, mbrsh TYPE mara-mbrsh, mtart TYPE mara-mtart, ersda TYPE mara-ersda, packcode TYPE mara-packcode, END OF ty_result. DATA: lt_result TYPE TABLE OF ty_result, lo_result_set TYPE REF TO cl_sql_result_set, lx_sql TYPE REF TO cx_sql_exception. DATA: QUERY TYPE STRING, Q2 TYPE STRING, MAINQUERY TYPE STRING. QUERY = | SELECT MATNR, MBRSH, MTART, ERSDA, PACKCODE FROM MARA |. Q2 = | WHERE MBRSH = 'M' |. CONCATENATE QUERY Q2 INTO MAINQUERY. TRY. lo_result_set = NEW cl_sql_statement( )->execute_query( mainquery ). lo_result_set->set_param_table( REF #( lt_result ) ). " Get result lo_result_set->next_package( ). lo_result_set->close( ). CATCH cx_sql_exception INTO lx_sql. " Error handling WRITE: lx_sql->get_text( ). ENDTRY. IF lt_result IS NOT INITIAL. DATA: o_alv TYPE REF TO cl_salv_table. DATA: lx_msg TYPE REF TO cx_salv_msg. TRY. cl_salv_table=>factory( IMPORTING r_salv_table = o_alv CHANGING t_table = lt_result ). CATCH cx_salv_msg INTO lx_msg. ENDTRY. ENDIF. o_alv->display( ). 符号与大多数数据库不兼容,列通常需要使用逗号/大小写。

有几种方法可以完成此任务:您也可以使用已弃用的~generate subroutine pool,但现在强烈建议不要使用这些结构。 ABDC是最简单和最新的,正如Oguz明智地说的那样。