SAP Business One SQL Views: Reusable Queries Step-by-Step - featured image

Publications

SQL Views in SAP Business One: Reusable Queries Step-by-Step

Hector Pincheira

Hector Pincheira

CIO | CTO
Digital Strategy & Technology Innovation

items

If you work with reports in SAP Business One, you probably know the symptom: the same SQL query copied and pasted into five different places, with small variations, and nobody remembers which one is the correct version. The SQL views in SAP Business One solve exactly that chaos, because they let you encapsulate the business logic once and reuse it across the whole system. As a result, you stop maintaining ten copies of the same query and move to maintaining a single source of truth.

This is no minor technical detail. It's the difference between a reporting system that scales and one that becomes ungovernable as your company grows. So in this tutorial you'll learn to create, consume and maintain SQL views in a practical way, with code ready for SQL Server and for SAP HANA.

SAP Business One SQL views - reusable data layer for reports
A SQL view acts as a reusable logical layer over your SAP Business One data.

What a SQL view is and why your company needs one

A view is essentially a saved query that behaves as if it were a table. When you create it, you define the logic once —the joins, the filters, the calculations— and then any tool can read it with a simple SELECT. The view doesn't store physical data, though: every time you query it, it runs the underlying logic against the real tables and returns information that is always current.

For an IT manager, the value is strategic. First, you centralize business rules: if the way margin is calculated changes, you fix it in a single object and every report updates automatically. You also simplify your team's work, because an analyst can query V_VentasMargen without understanding the six joins behind it. As a result, you reduce errors and speed up delivery of information.

For example, views are the ideal foundation for feeding Crystal Reports, dashboards, Excel exports or any external Business Intelligence tool. That way, one well-designed view becomes the foundation of dozens of consistent reports.

Prerequisites before creating SQL views in SAP Business One

Before you start, you need a few things in place. First, you need direct database access through SQL Server Management Studio (for SQL Server installations) or SAP HANA Studio / HANA Database Explorer (for HANA installations). Views are created at the database level, not from the SAP Query Manager.

Second, you need object creation permissions on the company database. So coordinate with your database administrator if you don't have them. It's also worth knowing the recommended convention: always prefix your views with something like V_ o U_ to distinguish them from standard SAP objects. That way you avoid conflicts during future system upgrades.

A critical point many people ignore: SAP does not officially support modifying its database schema, but creating read-only views is an accepted and safe practice, because it alters neither tables nor data. That said, never use a view to try to insert or update records; that always has to go through the interface, the DI-API or the Service Layer.

Step-by-step tutorial: your first reusable view

Let's start with a real and frequent case: a view that combines invoices, line detail and customers to calculate gross margin per line. This calculation tends to repeat across multiple reports, so it's the perfect candidate to encapsulate once.

The process has three steps. First, you write and validate the SELECT. Then you wrap it in a CREATE VIEW. Finally, you query the view wherever you need it. Here's the code on both platforms.

SQL Server

-- Create the margin-per-invoice-line view (SQL Server)
CREATE VIEW [dbo].[V_VentasMargen] AS
SELECT
    T0.[DocNum]      AS 'Invoice',
    T0.[DocDate]     AS 'Date',
    T2.[CardName]    AS 'Customer',
    T1.[ItemCode]    AS 'Code',
    T1.[Dscription]  AS 'Item',
    T1.[Quantity]    AS 'Quantity',
    T1.[LineTotal]   AS 'Sales',
    (T1.[StockPrice] * T1.[Quantity]) AS 'Cost',
    (T1.[LineTotal] - (T1.[StockPrice] * T1.[Quantity])) AS 'GrossMargin'
FROM OINV T0
INNER JOIN INV1 T1 ON T0.[DocEntry] = T1.[DocEntry]
INNER JOIN OCRD T2 ON T0.[CardCode] = T2.[CardCode]
WHERE T0.[CANCELED] = 'N';

SAP HANA

-- Create the margin-per-invoice-line view (SAP HANA)
CREATE VIEW "V_VentasMargen" AS
SELECT
    T0."DocNum"      AS "Invoice",
    T0."DocDate"     AS "Date",
    T2."CardName"    AS "Customer",
    T1."ItemCode"    AS "Code",
    T1."Dscription"  AS "Item",
    T1."Quantity"    AS "Quantity",
    T1."LineTotal"   AS "Sales",
    (T1."StockPrice" * T1."Quantity") AS "Cost",
    (T1."LineTotal" - (T1."StockPrice" * T1."Quantity")) AS "GrossMargin"
FROM OINV T0
INNER JOIN INV1 T1 ON T0."DocEntry" = T1."DocEntry"
INNER JOIN OCRD T2 ON T0."CardCode" = T2."CardCode"
WHERE T0."CANCELED" = 'N';

Note the fundamental difference between the two platforms: SQL Server uses square brackets and the schema [dbo], while HANA requires double quotes for column names and aliases. So you can't copy the same query from one environment to the other without adjusting it.

How to consume the view from any tool

Once created, the view behaves like just another table. As a result, you can filter, sort or group it however you like. For example, to get the margin on the current year's sales:

SQL Server

SELECT [Customer], SUM([Sales]) AS 'Sales', SUM([GrossMargin]) AS 'Margin'
FROM [dbo].[V_VentasMargen]
WHERE [Date] >= '20260101'
GROUP BY [Customer]
ORDER BY 'Margin' DESC;

SAP HANA

SELECT "Customer", SUM("Sales") AS "Sales", SUM("GrossMargin") AS "Margin"
FROM "V_VentasMargen"
WHERE "Date" >= '2026-01-01'
GROUP BY "Customer"
ORDER BY "Margin" DESC;

Notice something powerful: the complex join logic no longer appears. That way, anyone on your team can build reports on reliable data without touching the underlying logic.

SAP Business One SQL views - reporting dashboard fed by reusable views
Views feed BI dashboards and reports from a single source of truth.

Variations and use cases for SQL views

The real power shows up when you create views for different purposes. Here are two examples that cover very common needs and, along the way, show key syntax differences between the platforms.

Aggregated monthly sales view

This view summarizes sales by year and month, ideal for feeding a trend chart. Connecting it to a dashboard, for example, gives you the evolution of the business without recalculating anything each time.

SQL Server

CREATE VIEW [dbo].[V_VentasMensuales] AS
SELECT
    YEAR(T0.[DocDate])  AS 'Year',
    MONTH(T0.[DocDate]) AS 'Month',
    SUM(T0.[DocTotal])  AS 'TotalSales',
    COUNT(T0.[DocEntry]) AS 'NumInvoices'
FROM OINV T0
WHERE T0.[CANCELED] = 'N'
GROUP BY YEAR(T0.[DocDate]), MONTH(T0.[DocDate]);

SAP HANA

CREATE VIEW "V_VentasMensuales" AS
SELECT
    YEAR(T0."DocDate")  AS "Year",
    MONTH(T0."DocDate") AS "Month",
    SUM(T0."DocTotal")  AS "TotalSales",
    COUNT(T0."DocEntry") AS "NumInvoices"
FROM OINV T0
WHERE T0."CANCELED" = 'N'
GROUP BY YEAR(T0."DocDate"), MONTH(T0."DocDate");

Customer aging view

This view identifies inactive customers by calculating how many days have passed since their last purchase. Here you hit one of the most important differences between the platforms: date calculation. So pay attention to the change in functions.

SQL Server

CREATE VIEW [dbo].[V_AntiguedadClientes] AS
SELECT
    T0.[CardCode] AS 'Code',
    T0.[CardName] AS 'Customer',
    MAX(T1.[DocDate]) AS 'LastPurchase',
    DATEDIFF(DAY, MAX(T1.[DocDate]), GETDATE()) AS 'DaysSincePurchase'
FROM OCRD T0
INNER JOIN OINV T1 ON T0.[CardCode] = T1.[CardCode]
WHERE T0.[CardType] = 'C'
GROUP BY T0.[CardCode], T0.[CardName];

SAP HANA

CREATE VIEW "V_AntiguedadClientes" AS
SELECT
    T0."CardCode" AS "Code",
    T0."CardName" AS "Customer",
    MAX(T1."DocDate") AS "LastPurchase",
    DAYS_BETWEEN(MAX(T1."DocDate"), CURRENT_DATE) AS "DaysSincePurchase"
FROM OCRD T0
INNER JOIN OINV T1 ON T0."CardCode" = T1."CardCode"
WHERE T0."CardType" = 'C'
GROUP BY T0."CardCode", T0."CardName";

As you can see, SQL Server uses DATEDIFF(DAY, ...) and GETDATE(), while HANA uses DAYS_BETWEEN(...) and Current date. Likewise, where SQL Server uses ISNULL(), HANA uses IFNULL(). So migrating views between the two engines always requires a careful review of these functions.

SAP Business One SQL views - SQL Server and HANA database infrastructure
SQL Server and SAP HANA share the same table structure, but differ in function syntax.

Best practices and common mistakes

A badly designed view can turn into a performance problem. So it's worth following a few rules that separate a professional IT team from an improvised one.

First, always name your views with a clear prefix, such as V_. That way anyone immediately recognizes it as a custom object and not a standard SAP one. Also, document the purpose of each view in a central register; your future self will thank you.

Second, avoid SELECT * inside the view definition. Instead, specify only the columns you actually need. As a result, you improve performance and avoid surprises when SAP adds columns in an update. Likewise, be careful about nesting views inside other views, because it can silently degrade performance.

Third, remember to review your views after every SAP Business One upgrade. Read-only views are safe, but a major update could change field names. For example, if a view stops working after an upgrade, the most likely cause is that a referenced column changed. To modify an existing view, simply replace it:

SQL Server

-- Drop and recreate if you need to change the definition (SQL Server)
IF OBJECT_ID('dbo.V_VentasMargen', 'V') IS NOT NULL
    DROP VIEW [dbo].[V_VentasMargen];
GO
-- Then run your updated CREATE VIEW again

SAP HANA

-- Drop and recreate if you need to change the definition (SAP HANA)
DROP VIEW "V_VentasMargen";
-- Then run your updated CREATE VIEW again

Finally, a common mistake: forgetting the filter CANCELED = 'N' o WHERE on cancelled documents. As a result, reports inflate the figures by including voided documents. Always check that your logic excludes what doesn't belong.

Official SAP Resources

To go deeper, SAP offers valuable documentation. In particular, review the guide Best Practices of SQL in the SAP HANA Database, which details the syntax differences between HANA and standard SQL. The SAP Help Portal documentation on the Query Manager and the Service Layer is also required reading, especially from version 10.0 onward, which allows SQL queries to be run directly via the Service Layer without creating a view first. That said, views remain the more robust option when you need massive reuse and compatibility with external BI tools.

Conclusion: turn the chaos into a single source of truth

The SQL views in SAP Business One are not a technical trick; they're an architectural decision. When you centralize your business logic in well-named, well-documented views, you turn a fragile reporting system into a reliable, scalable information platform. So every hour you invest in designing good views multiplies into hours saved across your whole team.

The next step is yours. Find that query you've copied and pasted over and over, turn it into a view and watch your reporting operation gain order immediately. If you lead technology in your company, this is exactly the kind of quiet improvement that separates an IT function that fights fires from one that builds competitive advantage.

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