简体   繁体   English

如何在SAP HANA标量用户定义函数(UDF)中编写SQL语句?

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

I am writing a UDF (User Defined Function) in SAP HANA. 我在SAP HANA中编写UDF(用户定义函数)。 I want to use this function in another SQL statement outside. 我想在外面的另一个SQL语句中使用此函数。

Example: 例:

I want to write a UDF like 我想写一个UDF

func_get_age (in_employee_id)

This function takes in in_employee_id as an input parameter. 此函数接受in_employee_id作为输入参数。 Inside the UDF, it performs a lookup on a table for the particular in_employee_id and returns the age. 在UDF内,它在表上针对特定的in_employee_id执行查找并返回年龄。 So, a SQL goes inside the UDF. 因此,在UDF中使用了SQL。 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. 现在,此Age需要作为输出返回,然后由另一个SQL使用。 Something like 就像是

SELECT func_get_age(11234) from dummy;

My question is 我的问题是

Is it possible to write SQL inside UDFs in SAP HANA? 是否可以在SAP HANA中的UDF中编写SQL? Again i want the UDF to return a single value rather than a Table. 我再次希望UDF返回单个值而不是表。 I am not looking for Table Functions. 我不是在寻找表函数。

Yes, that's perfectly possible in current HANA releases. 是的,在当前的HANA版本中完全有可能。

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 . 该操作的结果分配给RETURN参数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 是的,请确保您可以按照返回员工全名的示例中的示例在HANA数据库上创建用户定义的标量函数

I copy a simplified version of the HANA UDF function below 我在下面复制了HANA UDF函数的简化版本

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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