简体   繁体   中英

How to write SQL statements in SAP HANA Scalar User Defined Functions (UDF)?

I am writing a UDF (User Defined Function) in SAP HANA. I want to use this function in another SQL statement outside.

Example:

I want to write a UDF like

func_get_age (in_employee_id)

This function takes in in_employee_id as an input parameter. Inside the UDF, it performs a lookup on a table for the particular in_employee_id and returns the age. So, a SQL goes inside the UDF. Something like

SELECT AGE FROM EMPLOYEE WHERE EMPLOYEE_ID = in_employee_id

Now this Age needs to be returned back as an output which is then consumed by another SQL. Something like

SELECT func_get_age(11234) from dummy;

My question is

Yes, that's perfectly possible in current HANA releases.

For example:

create or replace function multi (in mult int)
returns multi_count int
as 
begin
declare cnt integer;

    select count(*) into cnt 
    from objects;

    multi_count := :cnt * :mult;
end;

This function takes the number of all visible objects and multiplies it with the input parameter value. The result of this operation is assigned to the RETURN parameter multi_count .

select multi (3) from dummy;

Yes, sure You can create user-defined scalar function on HANA database as given in the sample where fullname of the employee is returned

I copy a simplified version of the HANA UDF function below

CREATE FUNCTION fnGetFullname (
 firstName VARCHAR(40),
 middleName VARCHAR(40),
 lastName VARCHAR(40)
)
returns fullname VARCHAR(120)
AS
BEGIN

fullname := CONCAT(CONCAT(CONCAT(firstName, ' '), CONCAT(middleName,' ')),lastName);

END 

You just assign a value to the return value

Here how you can use the function

select fnGetFullname('Sith Lord','Darth','Vader') from dummy;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM