2017-12-13 4 views
1

Microsoft Sql Serverでは、出力パラメータと選択結果の両方を使用してデータをクライアントに返すことができます。これはページングのようなユースケースに便利です。ここでは、総ページ数などの関連するメタデータと共にメインセットを返す必要があります。これまで私がPostgresで見てきたすべての例は、出力パラメータを介して、またはテーブル結果を介してデータを返します。私はそれが次のエラーで失敗したとして一緒の両方でプロシージャを作成することができません: ERROR:OUTとINOUT引数は表関数に許可されていないここPostgresql:Microsoft SQL Serverのように、ストアドプロシージャからテーブルデータと出力パラメータの両方を返す方法はありますか?

は、私が試したものです:

CREATE OR REPLACE FUNCTION fn_Test(out p_count int) 
RETURNS TABLE (CustomerId int, CustomerName varchar(50)) 
LANGUAGE 'plpgsql' 
AS $BODY$ 
BEGIN 

    INSERT INTO Customers(CustomerName, Address, Area, Phonenumber, Email, communicationpreference) 
    VALUES ('Julie Yellow', 'JY Ad', 'JY Ar', 'JV0987654', '[email protected]', 1); 

    SELECT COUNT(*) FROM CUSTOMERS INTO p_count; 
    SELECT CustomerId, CustomerName FROM Customers; 
EXCEPTION WHEN OTHERS THEN 
    RAISE exception '% %', SQLERRM, SQLSTATE; 
END; 
$BODY$ 

一緒に行くことはできませんか? PostgreSQLには別の方法がありますか?

答えて

1

をアドバイスしてください答えはノーです - あなたは関数が何かを返すか、何かがOUTパラメータで定義されていることを作成するのいずれか。

https://www.postgresql.org/docs/current/static/plpgsql-control-structures.html

If you declared the function with output parameters, write just RETURN with no expression. The current values of the output parameter variables will be returned.

ephasis鉱山。

https://www.postgresql.org/docs/current/static/sql-createfunction.html

Also OUT and INOUT arguments cannot be used together with the RETURNS TABLE notation

あなたは、単に最後のクエリで数を含めることができ

1

かかわらraise infoまたはnotifyチャンネルで遊ぶことができます。

しかし、あなたはreturn query

CREATE OR REPLACE FUNCTION fn_test() 
    RETURNS TABLE (customerid int, customername varchar(50), newcount int) 
AS $BODY$ 
BEGIN 

    INSERT INTO customers(customername, address, area, phonenumber, email, communicationpreference) 
    VALUES ('Julie Yellow', 'JY Ad', 'JY Ar', 'JV0987654', '[email protected]', 1); 

    return query 
     SELECT customerid, customername, count(*) over() as newcount 
     FROM customers; 
EXCEPTION WHEN OTHERS THEN 
    RAISE exception '% %', SQLERRM, SQLSTATE; 
END; 
$BODY$ 
LANGUAGE plpgsql; 

を使用する必要がPL/pgSQLのからクエリ結果を返すために、言語名は識別子であり、単一引用符に入れないでください。


また、関数から複数の結果を返すこともできます。しかし、これはほとんどのSQLクライアントで使用するには少しぎりぎりです:

CREATE OR REPLACE FUNCTION fn_test() 
    returns setof refcursor 
AS $BODY$ 
DECLARE 
    c1 refcursor; 
    c2 refcursor; 
BEGIN 

    INSERT INTO customers(customername, address, area, phonenumber, email, communicationpreference) 
    VALUES ('Julie Yellow', 'JY Ad', 'JY Ar', 'JV0987654', '[email protected]', 1); 

    open c1 for 
     select count(*) from customers; 
    return next c1; 

    open c2 for 
     SELECT customerid, customername 
     FROM customers; 
    return next c2; 

EXCEPTION WHEN OTHERS THEN 
    RAISE exception '% %', SQLERRM, SQLSTATE; 
END; 
$BODY$ 
LANGUAGE plpgsql; 
関連する問題