输入列表到存储过程

时间:2018-02-19 14:28:22

标签: sql hana

我从R获得了一个元素列表,我必须从数据库中获取属于元素列表的记录。

INPUT:

'12345','23456', '34567', '45678'

PROCEDURE:

   CREATE PROCEDURE "SCHEMA"."GET_RECORDS" (IN LIST (Type), OUT RECORDS tt_records)
   LANGUAGE SQLSCRIPT
    SQL SECURITY INVOKER 
READS SQL DATA AS
    BEGIN
    RECORDS = select * from TABLE where ids in :LIST
    END;

我如何向程序提供这样的清单?

2 个答案:

答案 0 :(得分:1)

将参数列表移交给SQLScript有点棘手,因为没有直接的原生构造。

一种方法是使用APPLY_FILTER函数并将列表“走私”为字符串参数。

在我的示例中,我从表CUSERS中读取并为APPLY_FILTER创建了一个过滤条件,该条件通过USER_ID子句过滤了列IN ( )

从列表中删除单引号(' ')是为了避免在执行查询时进行隐式类型转换。保留单引号会使IN ()子句看起来像这样:
IN ( '<1st value>', '<2nd value>', '<3rd value>', ...)
而不是 IN (<1st value>, <2nd value>, <3rd value>, ...)

CREATE PROCEDURE  "GET_RECORDS" (IN id_list VARCHAR(4000)
                                , OUT RECORDS tt_cusers)
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER 
    READS SQL DATA AS
BEGIN
declare _filter VARCHAR(4000);

    _users = select * from cusers;

    -- APPLY_FILTER expects a proper WHERE condition, so adding the column to filter
    -- and the IN () expression is necessary.
    -- 
    -- the the id_list comes in with single quotes, let's remove those

    _filter = 'USER_ID in (' || replace (:id_list, '''', '') ||')';
    RECORDS = APPLY_FILTER(:_users, :_filter);    
end;    

call get_records (?, ?)

-- this 'list' is to be used as a single parameter value
-- '131072', '161223', '131074'

将数据从SAP HANA导出到R的稍微更舒适的方法可以是使用表类型用户定义函数(UDF)。这里的主要区别是调用语句是一个简单的SELECT,结果只是这个SELECT的结果集。

CREATE function  "FGET_RECORDS" (IN id_list VARCHAR(4000))
returns  tt_cusers
LANGUAGE SQLSCRIPT
SQL SECURITY INVOKER 
    READS SQL DATA AS
BEGIN
declare _filter VARCHAR(4000);

    _users = select * from cusers;

    -- APPLY_FILTER expects a proper WHERE condition, so adding the column to filter
    -- and the IN () expression is necessary.
    -- 
    -- the the id_list comes in with single quotes, let's remove those

    _filter = 'USER_ID in (' || replace (:id_list, '''', '') ||')';
    _result = APPLY_FILTER(:_users, :_filter);    
    RETURN :_result;
end;    


select * from fget_records (? );

R(或任何其他客户端)中,确保在使用此构造时使用绑定变量。否则处理不同的字符串引用机制会变得很麻烦。

请参阅APPLY_FILTER here上的文档。

答案 1 :(得分:0)

使用用户定义的数据类型。

首先创建用户定义的数据类型

数据库节点&gt;可编程性&gt;类型&gt;用户定义的表类型

脚本:

CREATE TYPE dbo.MyTableType AS TABLE 
(
    ID INT
)

使用上述类型

在过程中创建参数
CREATE PROCEDURE usp_InsertMessages 
(
    @MyParameter MyTableType READONLY
)
AS
BEGIN

    INSERT INTO MyTable
    (
       id
    )
    SELECT 
       id
       FROM @MyParameter 

END
相关问题