agentleFS
logalitechlogalitech/abap-skills/skills/abap-sql-amdp/SKILL.md

abap-sql-amdp

Skill0 starsChanged 3 months agoMITView on GitHub

ABAP SQL moderno y empuje de cálculo a HANA: joins vs bucles, expresiones y funciones SQL, agregaciones, CTEs, y AMDP (procedimientos de base de datos). Úsala cuando el usuario optimice consultas, evite SELECT en bucles, use CASE/GROUP BY/WITH o escriba AMDP/SQLScript.

3 other projects use a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

1 rule. 0 are common, 1 is distinctive, and 0 are very specific to this project.

  • 0

    Common

    Most of the 3 edited versions we read keep these.

  • 1

    Distinctive

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    No uses AMDP por defecto: primero intenta ABAP SQL o CDS.

    line 100

“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

ABAP SQL & AMDP

Guía para escribir ABAP SQL moderno que empuje el cálculo a HANA (code pushdown), evite antipatrones de rendimiento y, cuando haga falta lógica de base de datos avanzada, use AMDP con SQLScript.

Cuándo y cómo usarla

  1. Identifica el objetivo: optimizar una consulta lenta, eliminar SELECT en bucles, agregar/agrupar datos o escribir un procedimiento HANA.
  2. Sitúa el contexto: mide primero (SQL trace, runtime analysis); no optimices a ciegas. Decide si basta ABAP SQL o necesitas AMDP.
  3. Aplica el principio de pushdown: haz que el cálculo ocurra en la base de datos y que ABAP reciba solo el resultado ya filtrado y agregado.

Regla de oro: nunca SELECT dentro de un bucle

El antipatrón de rendimiento más caro. Sustituye el bucle con acceso individual por un único acceso conjunto (FOR ALL ENTRIES o, mejor, un JOIN).

" ANTES: N accesos a base de datos (lento)
LOOP AT lt_orders INTO DATA(order).
  SELECT SINGLE name FROM I_Customer
    WHERE Customer = @order-customer
    INTO @DATA(name).
ENDLOOP.

" DESPUES: un unico JOIN, cálculo en HANA
SELECT o~SalesOrder, o~Customer, c~CustomerName
  FROM I_SalesOrder AS o
  INNER JOIN I_Customer AS c
    ON c~Customer = o~Customer
  WHERE o~OverallStatus = @status
  INTO TABLE @DATA(result).

Recuerda siempre el escape @ en las variables host (@status, @DATA(...)).

Expresiones, agregaciones y CTE

Empuja transformación, agregación y ramas condicionales a la sentencia SQL en lugar de recorrer la tabla interna en ABAP.

WITH
  +recent_orders AS (
    SELECT SalesOrder, Customer, TotalNetAmount, CreationDate
      FROM I_SalesOrder
      WHERE CreationDate >= @start_date )
SELECT Customer,
       COUNT( * )              AS OrderCount,
       SUM( TotalNetAmount )   AS TotalAmount,
       CASE WHEN SUM( TotalNetAmount ) > 100000 THEN 'A'
            WHEN SUM( TotalNetAmount ) > 10000  THEN 'B'
            ELSE 'C'
       END                     AS CustomerTier
  FROM +recent_orders
  GROUP BY Customer
  HAVING SUM( TotalNetAmount ) > 0
  ORDER BY TotalAmount DESCENDING
  INTO TABLE @DATA(customer_stats).

Con esto HANA hace el filtrado, la agregación y la clasificación; ABAP solo recibe el resultado final.

AMDP: lógica de base de datos en SQLScript

Cuando necesitas lógica de base de datos que ABAP SQL no cubre (bucles imperativos sobre datasets, tablas temporales, funciones HANA específicas), usa un método AMDP. Es una clase ABAP que implementa IF_AMDP_MARKER_HDB y cuyo cuerpo es SQLScript.

CLASS zcl_sales_amdp DEFINITION PUBLIC.
  PUBLIC SECTION.
    INTERFACES if_amdp_marker_hdb.
    METHODS get_top_customers
      IMPORTING VALUE(iv_year)     TYPE gjahr
      EXPORTING VALUE(et_result)   TYPE ztt_customer_stats.
ENDCLASS.

CLASS zcl_sales_amdp IMPLEMENTATION.
  METHOD get_top_customers BY DATABASE PROCEDURE
                           FOR HDB LANGUAGE SQLSCRIPT
                           OPTIONS READ-ONLY
                           USING i_salesorder.
    et_result = SELECT customer,
                       SUM( totalnetamount ) AS total_amount,
                       COUNT( * )            AS order_count
                  FROM i_salesorder
                  WHERE YEAR( creationdate ) = :iv_year
                  GROUP BY customer
                  ORDER BY total_amount DESC;
  ENDMETHOD.
ENDCLASS.

En AMDP: USING declara las fuentes de datos que consumes, OPTIONS READ-ONLY mejora el rendimiento en procedimientos de solo lectura, y los parámetros de entrada se referencian con : (por ejemplo :iv_year).

Buenas prácticas y errores comunes

  • Selecciona solo los campos que necesitas (FIELDS), nunca SELECT * a ciegas: menos transferencia y mejores planes.
  • Filtra y agrega en la base de datos, no en ABAP: recorrer una tabla interna grande para sumar es empujar el trabajo al sitio equivocado.
  • No uses AMDP por defecto: primero intenta ABAP SQL o CDS; AMDP solo cuando la lógica de datos no se expresa de otro modo. En ABAP Cloud, además, hay restricciones.
  • AMDP es específico de HANA: acopla el código a la base de datos; documenta esa dependencia.
  • Mide con SQL trace antes y después: la intuición sobre rendimiento suele fallar.

Referencias

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.