HANA database - Injection of a Table User Defined Function into a lateral join - hana

In short
On an HANA database, I have set a Table User Defined Function which returns a 1-row table with 3 columns ;
I would like to use it inside a lateral join but so far my attempts have been to no avail.
The problem
Let's say we have the following dummy Table User Defined Function :
CREATE OR REPLACE FUNCTION PBANALYST. F__ITEM_MBEW(
IN
p_str_MATNR NVARCHAR(18)
, p_str_BWKEY NVARCHAR(02)
, p_str_VALDATE NVARCHAR(08)
)
RETURNS
TABLE(
VALDATE NVARCHAR(08)
, LBKUM INTEGER
, VERPR DECIMAL
, STPRS DECIMAL
)
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER
AS
BEGIN
RETURN
SELECT
'20220928' AS VALDATE
, 10 AS LBKUM
, 5.3 AS VERPR
, 10.5 AS STPRS
FROM DUMMY
;
END;
It works fine on its own.
But when I try to inject it inside a lateral join, I get an error :
DO
BEGIN
tbl_MATNR_LIST =
SELECT '000000000000824151' AS MATNR , '92' AS div , '20220715' AS VALDATE FROM dummy
;
SELECT
tbl_MATNR_LIST. *
FROM :tbl_MATNR_LIST tbl_MATNR_LIST ,
LATERAL(
SELECT *
FROM F__ITEM_MBEW(
'000000000000824151'
, '92'
, '20220715'
)
) MBEW
;
END;
DataSource.Error : ODBC: ERROR [S1000] [SAP AG][LIBODBCHDB DLL][HDBODBC] General error;318 decimal precision specifier is out of range: -1: (1 to 38)
How can I fix it?
Thank you for your help.

The error message
DataSource.Error : ODBC: ERROR [S1000] [SAP AG][LIBODBCHDB DLL][HDBODBC] General error;318 decimal precision specifier is out of range: -1: (1 to 38)
can easily be fixed by specifying the decimal data type lengths in the user defined function:
TABLE(
VALDATE NVARCHAR(08)
, LBKUM INTEGER
, VERPR DECIMAL (10, 2)
, STPRS DECIMAL (10, 2)
)
Unfortunately, that does not help with the overall goal: to use the UDF in the LATERAL join in a meaningful way.
What does work is something like this:
DO
BEGIN
tbl_MATNR_LIST =
SELECT '000000000000824151' AS MATNR
, '92' AS div
, '20220715' AS VALDATE
FROM dummy;
SELECT
tml. *
FROM :tbl_MATNR_LIST tml
CROSS JOIN LATERAL(
F__ITEM_MBEW( '000000000000824151'
, '92'
, '20220715')
) MBEW;
END;
This does return the result, but obviously does not use any "lateral" references.
If one tries to make "grab stuff side-ways" this is the result:
[...]
CROSS JOIN LATERAL(
F__ITEM_MBEW( '000000000000824151'
, tml.div
, '20220715')
) MBEW;
[...]
SQL Error [7] [HY000]: SAP DBTech JDBC: [7] (at 292): feature not supported: non-field expression with LATERAL: line 13 col 29 (at pos 292)
At this point, I would guess that this way of using the LATERAL JOIN is just not supported (on version 2.00.057).

Related

Could someone help me understand the ambiguity here in Postgres?

So I've been trying out PG for a few days, specifically through NpgSQL in dotnet core, but I don't believe that is relevant to my question. I've been writing a couple of update functions. The first one was easy:
CREATE OR REPLACE FUNCTION "Api"."UpdateExpenseReceipt" ( "vReceiptID" UUID , "vTotal" DOUBLE PRECISION , "vTaxPercent" DOUBLE PRECISION , "vShippingCost" DOUBLE PRECISION , "vReceiptDate" TIMESTAMP , "vReference" VARCHAR , "vCurrentToken" UUID )
RETURNS TABLE ( ReceiptID UUID , Total DOUBLE PRECISION , TaxPercent DOUBLE PRECISION , ShippingCost DOUBLE PRECISION , Reference VARCHAR(96) , ReceiptDate TIMESTAMP )
LANGUAGE PLPGSQL
AS $$
DECLARE "iValidReceipt" INTEGER;
DECLARE "iValidUser" INTEGER;
BEGIN
"iValidReceipt" := ( SELECT COUNT("ReceiptID") FROM "Users"."ExpenseReceipt" WHERE "ReceiptID" = "vReceiptID" );
"iValidUser" := ( SELECT COUNT("AccountID") FROM "Users"."Account" WHERE "CurrentToken" = "vCurrentToken" LIMIT 1 );
IF "iValidUser" = 0 THEN
RAISE 'Error' USING ERRCODE = '10001';
END IF;
IF "iValidReceipt" > 0 THEN
UPDATE "Users"."ExpenseReceipt" SET
"Total" = COALESCE( "vTotal" , "Total" )
, "TaxPercent" = COALESCE( "vTaxPercent" , "TaxPercent" )
, "ShippingCost" = COALESCE( "vShippingCost" , "ShippingCost" )
, "Reference" = COALESCE( CAST( "vReference" AS VARCHAR ) , "Reference" )
, "ReceiptDate" = COALESCE( "vReceiptDate" , "ReceiptDate" )
, "EditDate" = current_timestamp at time zone 'utc'
WHERE "ReceiptID" = "vReceiptID";
RETURN QUERY
SELECT
"ReceiptID"
, "Total"
, "TaxPercent"
, "ShippingCost"
, "Reference"
, "ReceiptDate"
FROM "Users"."ExpenseReceipt"
WHERE "ReceiptID" = "vReceiptID";
ELSE
RAISE 'Error' USING ERRCODE = '10101';
END IF;
END; $$
--I'll include the table itself in case its relevant
CREATE TABLE "Users"."ExpenseReceipt"
(
"ReceiptID" UUID NOT NULL DEFAULT uuid_generate_v4(),
"AccountID" UUID NOT NULL ,
"Total" DOUBLE PRECISION NOT NULL ,
"TaxPercent" DOUBLE PRECISION DEFAULT 0.0 ,
"ShippingCost" DOUBLE PRECISION DEFAULT 0.0 ,
"Reference" VARCHAR(96) ,
"ReceiptDate" TIMESTAMP ,
"EditDate" TIMESTAMP DEFAULT ( current_timestamp at time zone 'utc' )
);
Easy update function, uses coalesce to not update the value if the API call doesn't set them. Everything works fine (after dealing through the numerous naming issues I've run into with postgres, and there I think NpgSQL is relevant). I know how to get it right. I made a second one, basically exactly the same:
CREATE OR REPLACE FUNCTION "Api"."UpdateSupplyItem" ( "vItemID" UUID , "vDescription" VARCHAR , "vSize" VARCHAR , "vNetCost" DOUBLE PRECISION , "vPackageQuantity" DOUBLE PRECISION , "vNetWeight" DOUBLE PRECISION , "vCurrentToken" UUID )
RETURNS TABLE ( "ItemID" UUID , "Description" VARCHAR , "Size" VARCHAR , "NetCost" DOUBLE PRECISION , "PackageQuantity" DOUBLE PRECISION , "NetWeight" DOUBLE PRECISION )
LANGUAGE PLPGSQL
AS $$
DECLARE "iValidItem" INTEGER;
DECLARE "iValidUser" INTEGER;
BEGIN
"iValidItem" := ( SELECT COUNT(usi."ItemID") FROM "Users"."SupplyItem" usi WHERE usi."ItemID" = "vItemID" );
"iValidUser" := ( SELECT COUNT("AccountID") FROM "Users"."Account" WHERE "CurrentToken" = "vCurrentToken" LIMIT 1 );
IF "iValidUser" = 0 THEN
RAISE 'Error' USING ERRCODE = '10001';
END IF;
IF "iValidItem" > 0 THEN
UPDATE "Users"."SupplyItem"
SET
"Description" = COALESCE( "vDescription" , "Users"."SupplyItem"."Description" )
, "Size" = COALESCE( "vSize" , "Users"."SupplyItem"."Size" )
, "NetCost" = COALESCE( "vNetCost" , "Users"."SupplyItem"."NetCost" )
, "PackageQuantity" = COALESCE( "vPackageQuantity" , "Users"."SupplyItem"."PackageQuantity")
, "NetWeight" = COALESCE( "vNetWeight" , "Users"."SupplyItem"."NetWeight" )
WHERE "Users"."SupplyItem"."ItemID" = "vItemID";
RETURN QUERY SELECT usi."ItemID" , usi."Description" , usi."Size" , usi."NetCost" , usi."PackageQuantity" , usi."NetWeight" FROM "Users"."SupplyItem" usi WHERE usi."ItemID" = "vItemID" LIMIT 1;
ELSE
RAISE 'Error' USING ERRCODE = '10401';
END IF;
END; $$
--Again, the table in case it helps
CREATE TABLE "Users"."SupplyItem"
(
"ItemID" UUID NOT NULL DEFAULT uuid_generate_v4() ,
"AccountID" UUID NOT NULL ,
"Description" VARCHAR ,
"Size" VARCHAR ,
"NetCost" DOUBLE PRECISION ,
"PackageQuantity" DOUBLE PRECISION ,
"NetWeight" DOUBLE PRECISION
);
but it's quite different. You can see clearly that I've had to fully qualify the right hand side of every equals (where the earlier function had no need). I get ambiguity all the way down the update statement. It starts at ItemID, then Description, then Size... every attribute I think. First thing I did was alias the table
UPDATE usi [...] FROM "Users"."SupplyItem" usi
but that failed because you can't do short aliasing in an UPDATE in PG (relation usi."[...]" does not exist") which actually kind of sucks. I only figured out that it needed to be fully qualified when someone asked a similar question and the answer was "It must be a quirk of RETURNS TABLE."
So why is my second update "a quirk" but my first update works perfectly? I've had a tough time with PG (and I'm not a slouch), but having two functions that seem identical having entirely different results (at runtime no less) makes me uncomfortable. I'm posting here because I know the two functions must be markedly different; 99.9% of the time, there is no such thing as a "quirk." There is something I need to understand to work around to avoid in the future. What is the "gotcha" that I've missed in the second UPDATE function?
The problem is that you have a function variable "Size" (an OUT parameter defined in the RETURNS TABLE clause) and a column "Size" in "Users"."SupplyItem". So you have to qualify the reference to indicate what you mean.
I recommend using an alias for simplicity:
UPDATE "Users"."SupplyItem" AS si
SET "Size" = COALESCE("vSize" , si."Size")
...
There is no such ambiguity in your first example, because you didn't double quote the parameter TaxPercent, so it gets case folded to taxpercent and is different from the column "TaxPercent".

SQL Error Converting Data to Int When I am Not Asking It To

I have the following SQL statement. In it I need to convert some numbers stored as varchar to decimal in order to sum them.
When I run this SQL against my constraints I get this message:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '1635.34' to data
type int.
Which baffles me because I am casting my data as decimal. It also baffles me because when I use different constraints that have the same type of data in the field (1234.56 type of format) it works. That data is in the TotalPremium field.
(My logic is a bit complex so that is why SQL statement is complex. I am posting all of it for clarity sake. Also, redesigning database table field type is not an option at this point.)
SELECT Account_No, version_num, LineOfBus, ProductNo, QuoteNo, Sum(Cast(TotalPremium as Decimal(16,2))) TotalPremium
FROM
(SELECT t.Account_No, t.version_num,
CASE
WHEN t.PackageIndicator = '1' THEN 'Package' Else t.Lob
END AS LineOfBus,
t.ProductNo, t.QuoteNo, Cast(COALESCE(t.TotalPremium,0) as decimal(16,2)) TotalPremium
FROM uAccountProductInfo as T
WHERE t.version_num IN
(SELECT sqVersionNumber.version_num
FROM
/* this captures unique package product records (or just stand alone records as well) */
(SELECT DISTINCT sqUnique.version_num, Count(sqUnique.version_num) VersionCount
FROM
/* grab list of all uniquer version, product, quote combinations (use distinct to combine package */
(SELECT DISTINCT version_num, productNo, quoteNo
FROM uAccountProductInfo
WHERE Account_No = '1172014' /* pass as parameter */
AND ProductNo IN ('6472930', '6474927') /* pass as parameter */
AND QuoteNo IN ('724185-01', '881957-08') /* pass as parameter */
) AS sqUnique
GROUP BY version_num
HAVING Count(version_num) = 2 /* pass as variable based on number of products, quotes */
) as sqVersionNumber
)
AND t.Account_no = '1172014' /* pass as parameter */
AND t.ProductNo IN ('6472930', '6474927') /* pass as parameter */
AND t.QuoteNo IN ('724185-01', '881957-08') /* pass as parameter */) as sqLOB
GROUP BY Account_No, version_num, LineOfBus, ProductNo, QuoteNo
The problem is that SQL Server does not guarantee the order of evaluation of operations. You clearly have something improper in the field. In SQL Server 2012+, use try_convert():
SELECT Sum(try_convert(decimal(16, 2), TotalPremium ))) as TotalPremium
In earlier versions, use case:
SELECT Sum(case when isnumeric(TotalPremium) = 1 then convert(decimal(16, 2), TotalPremium)) end) as TotalPremium
isnumeric() is not perfect, but it should be good enough for your purposes.
Cast t.TotalPremium to decimal before coalescing. Your query is doing coalesce on a string and an integer, then casting the result to decimal. Try using0.0instead of0as well.
edit I do not actually think using 0.0 rather than 0 is a good idea, aside from readability. If that is the goal, cast it to the same decimal datatype. Otherwise, this could be construed as a datatype dominant over decimal. 0 as int or varchar should not take precedence over our value casted to a decimal.
You could use isnull() instead of coalesce(), though it would still be better practice to use the same datatype as RexMaison points out.
create table t (TotalPremium varchar(16));
insert into t values (''),(null),('1635.34');
/* no error */
select isnull(t.TotalPremium,0)
from t;
/* no error */
select coalesce(t.TotalPremium,'0')
from t;
/* error */
select coalesce(t.TotalPremium,0)
from t;
rextester demo: http://rextester.com/OHEJ71310
Just posting final code that worked after incorporating elements of all 3 answers.
SELECT Account_No, version_num, LineOfBus, ProductNo, QuoteNo,
SUM(CASE
WHEN ISNUMERIC(TotalPremium) = 1 THEN CONVERT(decimal(16,2),TotalPremium)
END) As TotalPremium
FROM
(SELECT t.Account_No, t.version_num,
CASE
WHEN ISNull(t.PackageIndicator,'0') = '1' THEN 'Package' Else t.Lob
END AS LineOfBus,
t.ProductNo, t.QuoteNo,
ISNull(CASE
WHEN ISNUMERIC(t.TotalPremium) = 1 THEN CONVERT(decimal(16,2),t.TotalPremium)
END, 0) TotalPremium
FROM uAccountProductInfo as T
WHERE t.version_num IN
(SELECT sqVersionNumber.version_num
FROM
/* this captures unique package product records (or just stand alone records as well) */
(SELECT DISTINCT sqUnique.version_num, Count(sqUnique.version_num) VersionCount
FROM
/* grab list of all uniquer version, product, quote combinations (use distinct to combine package */
(SELECT DISTINCT version_num, productNo, quoteNo
FROM uAccountProductInfo
WHERE Account_No = '1172014' /* pass as parameter */
AND ProductNo IN ('6472930', '6474927') /* pass as parameter */
AND QuoteNo IN ('724185-01', '881957-08') /* pass as parameter */
) AS sqUnique
GROUP BY version_num
HAVING Count(version_num) = 2 /* pass as variable based on number of products, quotes */
) as sqVersionNumber
)
AND t.Account_no = '1172014' /* pass as parameter */
AND t.ProductNo IN ('6472930', '6474927') /* pass as parameter */
AND t.QuoteNo IN ('724185-01', '881957-08') /* pass as parameter */) as sqLOB
GROUP BY Account_No, version_num, LineOfBus, ProductNo, QuoteNo

Error creating function in DB2 with params

I have a problem with a function in db2
The function finds a record, and returns a number according to whether the first and second recorded by a user
The query within the function is this
SELECT
CASE
WHEN NUM IN (1,2) THEN 5
ELSE 2.58
END AS VAL
FROM (
select ROW_NUMBER() OVER() AS NUM ,s.POLLIFE
from LQD943DTA.CAQRTRML8 c
INNER JOIN LSMODXTA.SCSRET s ON c.MCCNTR = s.POLLIFE
WHERE s.NOEMP = ( SELECT NOEMP FROM LSMODDTA.LOLLM04 WHERE POLLIFE = '0010111003')
) AS T WHERE POLLIFE = '0010111003'
And works perfect
I create the function with this code
CREATE FUNCTION LIBWEB.BNOWPAPOL(POL CHAR)
RETURNS DECIMAL(7,2)
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
RETURN (
SELECT
CASE
WHEN NUM IN (1,2) THEN 5
ELSE 2.58
END AS VAL
FROM (
select ROW_NUMBER() OVER() AS NUM ,s.POLLIFE
from LQD943DTA.CAQRTRML8 c
INNER JOIN LSMODXTA.SCSRET s ON c.MCCNTR = s.POLLIFE
WHERE s.NOEMP = ( SELECT NOEMP FROM LSMODDTA.LOLLM04 WHERE POLLIFE = POL)
) AS T WHERE POLLIFE = POL
)
The command runs executed properly
WARNING: 17:55:40 [CREATE - 0 row(s), 0.439 secs] Command processed.
No rows were affected
When I want execute the query a get a error
SELECT LIBWEB.BNOWPAPOL('0010111003') FROM DATAS.DUMMY -- dummy has only one row
I get
[Error Code: -204, SQL State: 42704] [SQL0204] BNOWPAPOL in LIBWEB
type *N not found.
I detect, when I remove the parameter the function works fine!
With this code
CREATE FUNCTION LIBWEB.BNOWPAPOL()
RETURNS DECIMAL(7,2)
LANGUAGE SQL
NOT DETERMINISTIC
READS SQL DATA
RETURN (
SELECT
CASE
WHEN NUM IN (1,2) THEN 5
ELSE 2.58
END AS VAL
FROM (
select ROW_NUMBER() OVER() AS NUM ,s.POLLIFE
from LQD943DTA.CAQRTRML8 c
INNER JOIN LSMODXTA.SCSRET s ON c.MCCNTR = s.POLLIFE
WHERE s.NOEMP = ( SELECT NOEMP FROM LSMODDTA.LOLLM04 WHERE POLLIFE = '0010111003')
) AS T WHERE POLLIFE = '0010111003'
)
Why??
This statement:
SELECT LIBWEB.BNOWPAPOL('0010111003') FROM DATAS.DUMMY
causes this error:
[Error Code: -204, SQL State: 42704] [SQL0204] BNOWPAPOL in LIBWEB
type *N not found.
The parm value passed into the BNOWPAPOL() function is supplied as a quoted string with no definition (no CAST). The SELECT statement assumes that it's a VARCHAR value since different length strings might be given at any time and passes it to the server as a VARCHAR.
The original function definition says:
CREATE FUNCTION LIBWEB.BNOWPAPOL(POL CHAR)
The function signature is generated for a single-byte CHAR. (Function definitions can be overloaded to handle different inputs, and signatures are used to differentiate between function versions.)
Since a VARCHAR was passed from the client and only a CHAR function version was found by the server, the returned error fits. Changing the function definition or CASTing to a matching type can solve this kind of problem. (Note that a CHAR(1) parm could only correctly handle a single-character input if a value is CAST.)

How to use SDO_GEOM.SDO_CLOSEST_POINTS as Query with Oracle Spatial

I am trying to use SDO_GEOM.SDO_CLOSEST_POINTS purely as a sql query. All the examples use it in conjunction with pl/sql. Is it possible to use it in a query without pl/sql and could anyone provide an example of the syntax for how to do that?
My specific task is trying to return the vertex on a line that is closest to a point.
http://docs.oracle.com/cd/B28359_01/appdev.111/b28400/sdo_objgeom.htm#SPATL1113
Thank you.
It's not possible to call a PL/SQL procedure from an SQL query.
I would suggest that you create an Oracle object type that wraps the OUT parameters from SDO_GEOM.SDO_CLOSEST_POINTS and then define your own PL/SQL function that calls the procedure that returns an instance of your object type.
Something like this:
CREATE TYPE closest_points_type AS OBJECT (
dist NUMBER
, geoma mdsys.sdo_geometry
, geomb mdsys.sdo_geometry
)
/
CREATE FUNCTION sdo_closest_points_sql (
p_geom1 IN sdo_geometry
, p_geom2 IN sdo_geometry
, p_tolerance IN NUMBER
, p_unit IN VARCHAR2
)
RETURN closest_points_type
IS
l_dist NUMBER;
l_geoma mdsys.sdo_geometry;
l_geomb mdsys.sdo_geometry;
BEGIN
sdo_geom.sdo_closest_points(
geom1 => p_geom1
, geom2 => p_geom2
, tolerance => p_tolerance
, unit => p_unit
, dist => l_dist
, geoma => l_geoma
, geomb => l_geomb
);
RETURN closest_points_type(l_dist, l_geoma, l_geomb);
END sdo_closest_points_sql;
/
You should then be able to call this function from a SELECT statement, and interrogate the resulting object like so:
WITH q1 AS (
SELECT
sdo_closest_points_sql(
mdsys.sdo_geometry(2002, NULL, NULL, sdo_elem_info_array(1,2,1), sdo_ordinate_array(1,1, 1,10, 1,20))
, mdsys.sdo_geometry(2002, NULL, NULL, sdo_elem_info_array(1,2,1), sdo_ordinate_array(2,5, 2,15, 2,25))
, 0.05
, NULL
) result
FROM dual
)
SELECT
(q1.result).dist dist
, (q1.result).geoma geoma
, (q1.result).geomb geomb
FROM q1

Calculate percentage by using column value

I got a table with the below data in it.
all I need to do is a query the calculate 10% of the damage so I have done the below:
SELECT damage = (damage * 10) /100
,[Peril_Code]
FROM [LocExposure].[dbo].[myTable]
and this return the below result:
[Damage] column is a float .
I cannot figure out why it returns the wrong calculation.
Your output is correct. No error. Please check the result 2.44E-06 where your actual value was 2.44E-05.
So, there is no error.
UPDATE:
For avoiding scientific notation, you can go through the following post
convert float into varchar in SQL server without scientific notation
DECLARE #Damage TABLE
(
Damage FLOAT,
PerilCode CHAR(1)
)
INSERT INTO #Damage VALUES
(2.44253351044103E-05 , 'T'),
(0.000125444785042888 , 'T'),
(0.00015258112714104 , 'T'),
(0.000238995871781784 , 'T'),
(0.000267978447740977 , 'T')
SELECT Damage, Damage * 0.1 [10%], PerilCode
FROM #Damage
Output
Damage 10% PerilCode
---------------------------------------------------------
2,44253351044103E-05 2,44253351044103E-06 T
0,000125444785042888 1,25444785042888E-05 T
0,00015258112714104 1,5258112714104E-05 T
0,000238995871781784 2,38995871781784E-05 T
0,000267978447740977 2,67978447740977E-05 T