Skip to Content
Technical Articles

NEW!!! SAP Business One Service Layer – SQL Query

As of SAP Business One 10.0 FP 2011 you can directly create SQL queries via Service Layer and run them directly without previously requiring the creation of a view. This is a great feature that I’m happy to share as I’m sure you will appreciate!!!

Let me explain with some samples how you can easily use this feature. Full details are available in the document Working with SAP Business One Service Layer “4 SQL Query” chapter.

Check also this great video to see it in action!

Of course this feature is only to query data and not to update or post new data as you know SAP Business One database cannot be modified via SQL queries and only via the provided APIs (be it DI-API or Service Layer).

How to create a new query

The first step to run a query via Service Layer is to create the query with a POST request:

POST https://server:50000/b1s/v1/SQLQueries 
{
 "SqlCode": "MyNewSQLQuery",
 "SqlName": "GetItems",
 "SqlText": "select ItemCode, ItemName, ItmsGrpCod from OITM"
}

How to execute your sql query

Once the SQLQuery created you can execute your query via the List function.
The List function can be invoked in the following way with verb GET or POST:

GET https://server:50000/b1s/v1/SQLQueries('MyNewSQLQuery')/List
POST https://server:50000/b1s/v1/SQLQueries('MyNewSQLQuery')/List

Upon success, the service returns a JSON payload, containing the exact columns requested in the SQLQuery select clause.

{
 "odata.metadata" : "https://server:50000/b1s/v1/$metadata#SAPB1.SQLQueryResult",
 "SqlText" : "select [ItemCode], [ItemName], [ItmsGrpCod] from [OITM]",
 "value" : [
  {
    "ItemCode" : "i001",
    "ItemName" : "i001",
    "ItmsGrpCod" : 100
  },
  {
    "ItemCode" : "i002",
    "ItemName" : "i002",
    "ItmsGrpCod" : 100
  },
...
]
}

As you may imagine many options are available for this feature, here you have a short list I want to share with you, please check the documentation to get all the details.

SQL Keywords

You can create much more complex queries by using keywords like orderby, groupby, right join, left join, inner join,…

SQL Functions

Currently, only the aggregation functions and a limited set of other functions like sum, avg, max, min, left, right, distinct, count, lower, upper, isnull, ifnull,… are supported. More functions would be considered for support in future according to customers’ requirements. Don’t hesitate to create a request in our SAP Business Customer Influence session!

Allowed tables and fields

The documentation provides the full list of allowed tables you can query, we find of course OITM, OCRD, ORDR, OINV, OCRP, ORTT,… among many others.

By default for each table all fields can be read.
You can limit the columns you want to expose by configuring the fields to be excluded or included with the “ColumnExcludeList” and “ColumnIncludeList”:

{
  "TableList": [
    "ADM1",
    "ORDR",
    "CINF"
  ],
  "ColumnExcludeList": {
    "ORDR": [
    "CreateDate",
    "UpdateDate"
    ],
    "CINF": [
      "Algo",
      "AliasUpd",
      "TrailDays"
    ]
  },
  "ColumnIncludeList": {
    "ADM1": [
    "CurrPeriod",
    "Street"
    ]
  }
}​

Check the documentation for details on how to configure the AllowList file.

Queries with parameters

You can create queries with parameters, in the following example :docTotal is a parameter:

POST https://server:50000/b1s/v1/SQLQueries HTTP/1.1
{
 "SqlCode": "sql01",
 "SqlName": "queryOnOrder",
 "SqlText": "select DocEntry, DocTotal, DocDate, comments from ordr where DocTotal
> :docTotal"
}

Then when we execute the query we provide the parameter value either in the body if using a POST request:

POST https://server:50000/b1s/v1/SQLQueries('sql01')/List 
{
 "ParamList": "docTotal=10.1"
}

or in the URL if using a GET request:

GET https://server:50000/b1s/v1/SQLQueries('sql07')/List?docTotal=10.1 

Pagination 

The paging mechanism on the server side is a MUST for the List function of entity SQLQueries, as it can protect the server resource from exhausting in case there are millions of records returned in one roundtrip, or in the case of a careless user joining multiple big tables without applying correct filtering conditions.

The Service Layer allows clients to change the default paging size by specifying the following request header, but please don’t abuse of this option and keep the value as lower as possible to improve performances:

Prefer: odata.maxpagesize=5

SQLQueries CRUD Operations

You can of course get the list of SQLQueries available on your Service Layer as well as create, modify and delete SQLQueries. Please check the documentation for more details.

SQL Normalization

As you know the Service Layer supports both Microsoft SQL Server and SAP HANA databases. In order to provide a unified development experience the Service Layer internally parses and normalizes the raw SQL identifiers based on the underlying database.

I don’t want to repeat myself but I really recommend you to check the document Working with SAP Business One Service Layer “4 SQL Query” chapter to get all the details. This blog is just a short overview of the available capabilities!

Hope you will enjoy this new feature.

Let us know!

22 Comments
You must be Logged on to comment or reply to a post.
    • Hi Reynerio,

      As of SAP Business One 10.0 FP 2011, the Service Layer on Microsoft SQL Server and SAP HANA supports a highly flexible SQL Query.

      Please check the official documentation for more details and create a post in the SAP Community sharing what you have tested and the error message you get so other experts can help solving your issue.

      https://help.sap.com/doc/6ab840ef2e8140f3af9eeb7d8fef9f06/10.0/en-US/Working_with_SAP_Business_One_Service_Layer.pdf => Section 4. SQL Query

      Regards,
      Trinidad.

       

    • Hi Edgar,

      As of SAP Business One 10.0 FP 2011, the Service Layer on Microsoft SQL Server and SAP HANA supports a highly flexible SQL Query.

      Please check the official documentation for more details
      https://help.sap.com/doc/6ab840ef2e8140f3af9eeb7d8fef9f06/10.0/en-US/Working_with_SAP_Business_One_Service_Layer.pdf => Section 4. SQL Query

      Hope this helps
      Trinidad.

  • What a nice one!

    I am testing the new functionality and user data tables are not supported yet.

    I have tried to add a user data table in the list of allowed tables file, but the Service Layer reponses with "user defined table @XXXX Not Supportted ".

     

    Is expected that, in the future, SQLQuery can be performed on user data tables?.
    Thanks

    /
  • Hi,
    right now I am trying it, but in my case when I call the query it returns:

    502 Proxy Error
    The proxy server received an invalid response from an upstream server.
    The proxy server could not handle the request.
    Reason: Error reading from remote server502 Proxy Error

    Probably I will need increase ProxyTimeout :_(
    Regards Zdenek

    • Hi Zdenek Chládek

      We had been trying to make a sql query as you said, but we get with an error. Afeter many tries we make the conclusion that the problem is with user fields.
      Every time we try to select an user defined fiel we get an error (502), but if we do not place any user defined field in the query the query works as normal.
      Maria Trinidad MARTINEZ GEA  Any suggestion or idea?

      /
      • an example:

        GET /b1s/v1/SQLQueries('s1')/List
        
        
        
        
        {
        "SqlText": "select [U_F1] from [@MYTBL]",
        "value": [
        {
        "U_F1": "test data"
        },
        {
        "U_F1": "test data1"
        },
        {
        "U_F1": "i001"
        },
        {
        "U_F1": "i002"
        }
        ]
        }
        • Hi Txema,

          Have you tried to restart SL after adding the UDF?

          Can you please try with a simple query like my colleague Andy did? It works fine for him.

          If you cannot make it work after restart please create a support incident so it can be investigated further by our support team.

          Regards,

          Trinidad.

          • hi Maria Trinidad MARTINEZ GEA , Andy Bai

            I think that your Service Layer is working on a SQLServer enviroment. It´s Correct?.

            We are testing SQLQuery funcionality in SAP HANA enviroment.

             

            GET---> SQLQueries('sqlPPPP')

            {
                "odata.metadata": "https://SERVERNAME/b1s/v1/$metadata#SQLQueries/@Element",
                "odata.etag": "W/\"356A192B7913B04C54574D18C28D46E6395428AB\"",
                "SqlCode": "sqlPPPP",
                "SqlName": "PruebaSQLParams",
                "SqlText": "select \"U_USE\" from \"@NVT_FT_USO\"",
                "ParamList": null,
                "CreateDate": "2021-05-10",
                "UpdateDate": "2021-05-10"
            }

             

             

            GET-->SQLQueries('sqlPPPP')/List

            <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
            <html>
            
            <head>
            	<title>502 Proxy Error</title>
            </head>
            
            <body>
            	<h1>Proxy Error</h1>
            	<p>The proxy server received an invalid
            		response from an upstream server.<br />
            The proxy server could not handle the request<p>Reason: <strong>Error reading from remote server</strong></p>
            	</p>
            </body>
            
            </html>
            

             

             

            Thanks!!

  • Hello,

    I am trying to make a post call but I keep getting this error. Is there something I am missing or is the below not allowed?

    {
        "SqlCode": "WebItems",
        "SqlName": "GetWebItems",
        "SqlText": "SELECT (OnHand - IsCommited + OnOrder) as available FROM OITM  WHERE T0.U_WebItem  = 'Y'"
    }

    Error:

    {
       "error" : {
          "code" : 701,
          "message" : {
             "lang" : "en-us",
             "value" : "Invalid SQL syntax:, line 1, character position 14, mismatched input '-' expecting FROM"
          }
       }
    }
  • This is a really great feature. But two things are missing in my opinion:

    Firstly: Someone who is allowed to create queries should also be allowed to execute queries ad-hoc. Think of it like creating a query, executing it, then deleting it again.

    Secondly, and this is crucial: It must be possible to allow normal users to create queries (and/or execute ad-hoc queries) because otherwise this is almost useless for loosely-coupled third-party applications that are targeted for cloud deployments of SAP Business One.

    Currently only a superuser is allowed to create queries, and cloud operators don't give customers a superuser login. This means every time an updated third-party application needs a new query or a modification to an existing query, the cloud operators have to make a manual change, if they support doing that at all!

    If this issue was addressed, this feature would bring cloud-based deployments of SAP Business One a bit closer to the flexibility of on-premises deployments in terms of supporting third-party extensions.