SAP Business One Query Manager - featured image of the query audit tutorial

Publications

SAP Business One Query Manager: Audit and Organize Your Query Library

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

A company with eleven years of SAP Business One asked me for help with something else: a margin report that did not add up. Before looking at the report I asked for the list of saved queries. Nobody had one. What turned up, after half an hour of going screen by screen, were more than three hundred queries spread across four categories named General, New, Miscellaneous and Unclassified, with seven different versions of the same sales report and not one with an author anybody could identify without opening the database. Auditing the SAP Business One Query Manager stopped being a housekeeping task that morning.

The report was not the problem. That query library had become decision-making infrastructure without anyone treating it as such: the sales manager built his Monday meeting on a query called prueba3_ok. Therefore, the right question was no longer whether the numbers were correct. It was who answered for them.

This tutorial solves that headache with SQL. Below you will inventory your queries, detect orphans and duplicates, map which ones feed formatted searches and find those holding statements that do not belong. All in read-only mode, with both versions of every query: Microsoft SQL Server and SAP HANA.

Why auditing the SAP Business One Query Manager is not optional

A saved query looks harmless. In practice it is a small information system with no owner, no documentation and no life cycle. It also carries three risks that only show up once they already hurt.

Data risk. A query written four years ago against a warehouse structure that later changed still returns a number in the usual format, only the wrong one. Nobody questions it, because that report has been in use for years.

Permission risk. Access control lives in the category the query belongs to, and is managed from General Authorizations. However, the SQL runs exactly as written: it returns whatever it asks for, without filtering by data ownership or by branch. As a result, one badly built category is enough for someone to see costs or margins that are none of their business.

Performance risk. Old queries were written for databases that weighed a fraction of what they weigh today. A SELECT without a WHERE that used to return in seconds now keeps everyone who opens the same table waiting. Even so, almost nobody reviews the repository looking for that.

Prerequisites

  • SAP Business One 9.x or 10.x, on Microsoft SQL Server or SAP HANA.
  • Access to the Query Manager: Tools → Queries → Query Manager.
  • Authorization for Administration → System Initialization → Authorizations → General Authorizations, to review permissions by category.
  • A recent database backup. Every query in this article is read-only, but the backup is what lets you work without fear.

A detail that saves trouble: confirm which database you are standing on before you run anything. The Query Manager does not shout it, and test databases are usually named just like production ones, with a suffix that is read fast and read wrong.

SAP Business One Query Manager: the two tables behind it

The whole Query Manager fits in two tables. OUQR stores the queries and OQCN stores the categories. These are the fields that matter:

  • OUQR.IntrnalKey: internal identifier of the query. Yes, it is missing the letter e in Internal. It is a typo SAP has carried for decades and it will cost you three attempts every time you write it.
  • OUQR.QName: the name the user sees in the category tree.
  • OUQR.QString: the full SQL text, with capacity for 64,000 characters according to the SAP Business One SDK table reference.
  • OUQR.QCategory: the category, in numeric format.
  • OUQR.UserSign: the user who created the query, linked to OUSR.USERID.
  • OQCN.CategoryId and OQCN.CatName: identifier and name of each category.

The link between the two is direct: OUQR.QCategory = OQCN.CategoryId. Also, it is worth knowing from the start that QString is not ordinary text. In SQL Server it is ntext and in SAP HANA it is NCLOB, which means several common functions return poorly descriptive errors if you do not convert the field before using it.

There is something OUQR will not tell you: when each query was created, or who last modified it. It stores the original author and the text, and that is as far as it goes. That is why the inventory below relies on the name, the category and the creator. There is no more metadata to squeeze.

SAP Business One Query Manager: SQL code on screen during the query audit
Every saved query is code in production, even if nobody treats it that way.

Step by step: the full inventory of your library

Follow these five steps in order. The goal of this first pass is simple: to have a spreadsheet with all your queries, their category and their author.

  1. Open Tools → Queries → Query Manager and review which categories exist today.
  2. Create a new category called ZZ_Auditoria. This way, the queries in this article do not get mixed up with the mess you are about to measure.
  3. Open the Query Generator (Tools → Queries → Query Generator), paste the inventory query and click Execute.
  4. Export the result to Microsoft Excel using the export icon in the top toolbar.
  5. Save the query in the ZZ_Auditoria category with an explicit name, for example ZZ_Auditoria_01_Inventario.

The inventory query joins OUQR, OQCN and OUSR, and returns one row per query:

SQL Server

-- Full inventory of the query library
SELECT
    Q.IntrnalKey                                 AS ID_Consulta,
    Q.QName                                      AS Nombre,
    ISNULL(C.CatName, 'Sin categoria')           AS Categoria,
    ISNULL(U.USER_CODE, 'Desconocido')           AS Creador,
    ISNULL(U.U_NAME, '')                         AS Nombre_Creador,
    ISNULL(U.Locked, '?')                        AS Creador_Bloqueado,
    LEN(CAST(Q.QString AS NVARCHAR(MAX)))        AS Largo_SQL,
    LEFT(CAST(Q.QString AS NVARCHAR(MAX)), 150)  AS Inicio_SQL
FROM OUQR Q
LEFT JOIN OQCN C ON C.CategoryId = Q.QCategory
LEFT JOIN OUSR U ON U.USERID     = Q.UserSign
ORDER BY Categoria, Nombre;

SAP HANA

-- Full inventory of the query library
SELECT
    Q."IntrnalKey"                              AS "ID_Consulta",
    Q."QName"                                   AS "Nombre",
    IFNULL(C."CatName", 'Sin categoria')        AS "Categoria",
    IFNULL(U."USER_CODE", 'Desconocido')        AS "Creador",
    IFNULL(U."U_NAME", '')                      AS "Nombre_Creador",
    IFNULL(U."Locked", '?')                     AS "Creador_Bloqueado",
    LENGTH(Q."QString")                         AS "Largo_SQL",
    TO_NVARCHAR(SUBSTRING(Q."QString", 1, 150)) AS "Inicio_SQL"
FROM OUQR Q
LEFT JOIN OQCN C ON C."CategoryId" = Q."QCategory"
LEFT JOIN OUSR U ON U."USERID"     = Q."UserSign"
ORDER BY "Categoria", "Nombre";

Three columns deserve immediate attention. Creador_Bloqueado set to Y means the query was written by somebody who no longer operates in the system, and those are the first candidates for review. Largo_SQL above four thousand characters usually gives away a query that does too many things at once. Finally, Sin categoria repeated many times means the classification was never used, which is precisely the first problem to solve.

Detect orphan and duplicate queries

An orphan query is one nobody runs and no object in the system references. The most direct approach is to cross it against formatted searches, which are the most frequent automatic consumer. The table CSHS stores that assignment and points to the query through QueryID.

SQL Server

-- Queries not used by any formatted search
SELECT
    Q.IntrnalKey                       AS ID_Consulta,
    Q.QName                            AS Nombre,
    ISNULL(C.CatName, 'Sin categoria') AS Categoria,
    ISNULL(U.USER_CODE, 'Desconocido') AS Creador
FROM OUQR Q
LEFT JOIN OQCN C ON C.CategoryId = Q.QCategory
LEFT JOIN OUSR U ON U.USERID     = Q.UserSign
WHERE NOT EXISTS (SELECT 1 FROM CSHS S WHERE S.QueryID = Q.IntrnalKey)
ORDER BY Categoria, Nombre;

SAP HANA

-- Queries not used by any formatted search
SELECT
    Q."IntrnalKey"                        AS "ID_Consulta",
    Q."QName"                             AS "Nombre",
    IFNULL(C."CatName", 'Sin categoria')  AS "Categoria",
    IFNULL(U."USER_CODE", 'Desconocido')  AS "Creador"
FROM OUQR Q
LEFT JOIN OQCN C ON C."CategoryId" = Q."QCategory"
LEFT JOIN OUSR U ON U."USERID"     = Q."UserSign"
WHERE NOT EXISTS (SELECT 1 FROM CSHS S WHERE S."QueryID" = Q."IntrnalKey")
ORDER BY "Categoria", "Nombre";

A warning I write because it has cost me dearly: this list is no a deletion list. I once removed an obviously dead query on a Friday afternoon. By Monday the alert warning about orders above the credit limit had stopped arriving, and the sales team was left stranded for half a week until we found the cause. Alerts and approval procedures keep their references in their own template tables, so this cross-check does not see them. Review them by hand in the interface before touching anything.

Duplicates, on the other hand, are easy to hunt down. The idea is to group by the first characters of the SQL and count how many times that signature repeats. In addition, including the total length in the grouping reduces false positives from queries that start the same and diverge further down.

SQL Server

-- Duplicate queries by text signature
SELECT
    T.Firma,
    T.Largo,
    COUNT(*)      AS Copias,
    MIN(T.Nombre) AS Ejemplo_1,
    MAX(T.Nombre) AS Ejemplo_2
FROM (
    SELECT
        Q.QName                                                           AS Nombre,
        CAST(LEFT(CAST(Q.QString AS NVARCHAR(MAX)), 400) AS NVARCHAR(400)) AS Firma,
        LEN(CAST(Q.QString AS NVARCHAR(MAX)))                             AS Largo
    FROM OUQR Q
) T
GROUP BY T.Firma, T.Largo
HAVING COUNT(*) > 1
ORDER BY Copias DESC, T.Largo DESC;

SAP HANA

-- Duplicate queries by text signature
SELECT
    T."Firma",
    T."Largo",
    COUNT(*)        AS "Copias",
    MIN(T."Nombre") AS "Ejemplo_1",
    MAX(T."Nombre") AS "Ejemplo_2"
FROM (
    SELECT
        Q."QName"                                   AS "Nombre",
        TO_NVARCHAR(SUBSTRING(Q."QString", 1, 400)) AS "Firma",
        LENGTH(Q."QString")                         AS "Largo"
    FROM OUQR Q
) T
GROUP BY T."Firma", T."Largo"
HAVING COUNT(*) > 1
ORDER BY "Copias" DESC, T."Largo" DESC;

Two decisions in those queries are not decoration. First, the double CAST in the SQL Server version: the engine does not group by LOB types, so you have to convert ntext a NVARCHAR(MAX), trim it, and only then convert to a NVARCHAR of fixed length that the group by does accept. Without that step the error you get never mentions the word ntext anywhere. Second, I used a subquery instead of a CTE because the Query Generator gets along better with it.

SAP Business One Query Manager: manual review before retiring orphan queries
No query is retired without first checking who is using it.

SAP Business One Query Manager and formatted searches: the usage map

Knowing which queries are alive is worth more than knowing which ones are surplus. For example, before redesigning a user-defined field it pays to check whether any formatted search depends on it. This query delivers that complete map:

SQL Server

-- Map of formatted searches and their queries
SELECT
    S.FormID                           AS Formulario,
    S.ItemID                           AS Campo,
    S.ColID                            AS Columna,
    Q.IntrnalKey                       AS ID_Consulta,
    Q.QName                            AS Consulta,
    ISNULL(C.CatName, 'Sin categoria') AS Categoria
FROM CSHS S
INNER JOIN OUQR Q ON Q.IntrnalKey = S.QueryID
LEFT  JOIN OQCN C ON C.CategoryId = Q.QCategory
ORDER BY S.FormID, S.ItemID, S.ColID;

SAP HANA

-- Map of formatted searches and their queries
SELECT
    S."FormID"                            AS "Formulario",
    S."ItemID"                            AS "Campo",
    S."ColID"                             AS "Columna",
    Q."IntrnalKey"                        AS "ID_Consulta",
    Q."QName"                             AS "Consulta",
    IFNULL(C."CatName", 'Sin categoria')  AS "Categoria"
FROM CSHS S
INNER JOIN OUQR Q ON Q."IntrnalKey" = S."QueryID"
LEFT  JOIN OQCN C ON C."CategoryId" = Q."QCategory"
ORDER BY "Formulario", "Campo", "Columna";

The field FormID identifies the form and tells you where the search lives: 133 corresponds to the A/R invoice and 139 to the sales order, to name the two you will see most. ItemID points to the field within that form, and ColID to the column, when the search sits on a matrix. Keep this result next to the inventory, because it is the one you will check every time somebody proposes deleting something.

Risky queries: what should not be stored in there

The Query Manager is meant for reading. Even so, in every installation with a few years behind it there appear queries containing modification statements, saved at some point by a consultant in a hurry and forgotten ever since. This query locates them:

SQL Server

-- Queries containing statements other than SELECT
SELECT
 Q.QName AS Consulta,
 ISNULL(C.CatName, 'Sin categoria') AS Categoria,
 CASE
 WHEN CAST(Q.QString AS NVARCHAR(MAX)) LIKE '%DROP %' THEN 'DROP'
 WHEN CAST(Q.QString AS NVARCHAR(MAX)) LIKE 'LETE %' THEN 'DELETE'
 WHEN CAST(Q.QString AS NVARCHAR(MAX)) LIKE '%INSERT INTO%' THEN 'INSERT'
 WHEN CAST(Q.QString AS NVARCHAR(MAX)) LIKE '%UPDATE %' THEN 'UPDATE'
 ELSE 'REVISAR'
 END AS Sentencia_Detectada,
 LEFT(CAST(Q.QString AS NVARCHAR(MAX)), 200) AS Inicio_SQL
FROM OUQR Q
LEFT JOIN OQCN C ON C.CategoryId = Q.QCategory
WHERE CAST(Q.QString AS NVARCHAR(MAX)) LIKE '%DROP %'
 OR CAST(Q.QString AS NVARCHAR(MAX)) LIKE 'LETE %'
 OR CAST(Q.QString AS NVARCHAR(MAX)) LIKE '%INSERT INTO%'
 OR CAST(Q.QString AS NVARCHAR(MAX)) LIKE '%UPDATE %'
ORDER BY Sentencia_Detectada, Consulta;

SAP HANA

-- Queries containing statements other than SELECT
SELECT
 Q."QName" AS "Consulta",
 IFNULL(C."CatName", 'Sin categoria') AS "Categoria",
 CASE
 WHEN UPPER(Q."QString") LIKE '%DROP %' THEN 'DROP'
 WHEN UPPER(Q."QString") LIKE 'LETE %' THEN 'DELETE'
 WHEN UPPER(Q."QString") LIKE '%INSERT INTO%' THEN 'INSERT'
 WHEN UPPER(Q."QString") LIKE '%UPDATE %' THEN 'UPDATE'
 ELSE 'REVISAR'
 END AS "Sentencia_Detectada",
 TO_NVARCHAR(SUBSTRING(Q."QString", 1, 200)) AS "Inicio_SQL"
FROM OUQR Q
LEFT JOIN OQCN C ON C."CategoryId" = Q."QCategory"
WHERE UPPER(Q."QString") LIKE '%DROP %'
 OR UPPER(Q."QString") LIKE 'LETE %'
 OR UPPER(Q."QString") LIKE '%INSERT INTO%'
 OR UPPER(Q."QString") LIKE '%UPDATE %'
ORDER BY "Sentencia_Detectada", "Consulta";

The difference between the two versions is not cosmetic. SQL Server compares without distinguishing case under the usual collations, whereas HANA does distinguish, and that is why the HANA version carries UPPER. If your installation complains about the field type when applying that function, wrap the expression in TO_NVARCHAR over the first five thousand characters and move on.

Be ready for false positives as well. Comments inside the SQL and column aliases create noise, although the pattern with a trailing space avoids the most annoying case, which is confusing a field such as UpdateDate with an update statement. Review each result before you raise the alarm.

Variations and use cases

The base inventory allows one extension I use in every improvement project. It crosses the queries against the user-defined fields listed in CUFD and answers the question that always comes up: if I remove this field, what breaks?

SQL Server

-- User-defined fields referenced by saved queries
SELECT DISTINCT
    F.TableID        AS Tabla,
    'U_' + F.AliasID AS Campo_Usuario,
    F.Descr          AS Descripcion,
    Q.QName          AS Consulta_Que_Lo_Usa
FROM CUFD F
INNER JOIN OUQR Q
        ON CAST(Q.QString AS NVARCHAR(MAX)) LIKE '%U_' + F.AliasID + '%'
ORDER BY Tabla, Campo_Usuario, Consulta_Que_Lo_Usa;

SAP HANA

-- User-defined fields referenced by saved queries
SELECT DISTINCT
    F."TableID"         AS "Tabla",
    'U_' || F."AliasID" AS "Campo_Usuario",
    F."Descr"           AS "Descripcion",
    Q."QName"           AS "Consulta_Que_Lo_Usa"
FROM CUFD F
INNER JOIN OUQR Q
        ON Q."QString" LIKE '%U_' || F."AliasID" || '%'
ORDER BY "Tabla", "Campo_Usuario", "Consulta_Que_Lo_Usa";

That query compares every user-defined field against the text of every query. With four hundred fields and three hundred queries that is one hundred and twenty thousand text comparisons, so do not run it during peak hours. I schedule it overnight and read the result the next day.

The same inventory serves other purposes. For example, filtered with WHERE C.CatName = 'Finanzas' it lets you audit one area at a time, which is the only realistic way forward when there are hundreds of queries. Running it in production and in the test environment, and comparing in Excel, shows what was developed and never promoted.

Best practices and common mistakes when governing the SAP Business One Query Manager

The audit is worth little if you do not change the way you work afterwards. These are the rules I apply:

  • Mandatory naming convention: area, object and version, for example VEN_Margen_x_Cliente_v2. The record I have seen against that was fourteen queries called Ventas, told apart only by a number at the end.
  • One category per functional area, with authorization assigned from General Authorizations. The category is the only real access control you have over a query.
  • A commented header inside the SQL: author, date, purpose and who to ask. Since OUQR does not store dates, that comment is all the traceability you are going to get.
  • A two-stage retirement process. Rename with the ZZ_BAJA_ prefix and wait a full closing cycle before deleting. If somebody was using it, they will show up.

And the mistakes that cost the most:

  • Editing OUQR with direct statements. Modifying system tables outside the application leaves the database unsupported. To move queries between databases, use the interface or supported tools.
  • Deleting based on the orphan list without first reviewing alerts and approval procedures.
  • Leaving hard-coded values such as DocEntry = 4712 or a warehouse code typed by hand. They work for a month and mislead for years.
  • Assuming the category hides the data. It hides the query: anyone with permission on that category will see everything the SELECT returns.
SAP Business One Query Manager: query repository piled up without governance
A repository without conventions piles up versions until nobody knows which one is the good one.

Official SAP Resources

Conclusion

The first time I ran this inventory was on a 9.3, if memory serves, and the result on 10.0 has not changed much: there are always more queries than anybody remembered, and there is always at least one holding up an important decision without anyone having ever reviewed it. Auditing the Query Manager costs you one morning. Ignoring it costs considerably more, although the bill arrives in instalments and late.

Start with the inventory. With that spreadsheet in hand you will talk to each area about what gets used, what is duplicated and what can be retired, which is a different conversation from arguing whether a number is right or wrong.

In the Strategic Circle I publish tutorials like this one every week, with the queries ready to copy in both versions and the implementation detail that does not fit in a public article. If you lead IT at a company that already lives inside SAP Business One, that is where you want to be.

Most Read

QlikSense Hierarchy: parent-child chart of accounts expanded by levels
QlikSense Hierarchy: the Chart of Accounts That Doesn't Add Up
QlikSense Sum TOTAL: share of each family over the total
QlikSense Sum TOTAL: the Percentage That Changes When You Filter
SAP Business One Inventory Revaluation - featured image of the tutorial
SAP Business One Inventory Revaluation: Fix Wrongly Loaded Costs
Empty chamber with wooden benches: the counterweight that required being present to be used
The Veto You Had to Say in Person: Your Decisions With No Counterweight
SAP Business One customizations - featured image of the pre-upgrade audit tutorial
SAP Business One Customizations: Pre-Upgrade Audit
SAP Business One Customer Concentration - featured image of the tutorial
SAP Business One Customer Concentration: Measure Your Risk with SQL

RELATED ARTICLES