簡體   English   中英

在存儲過程中選擇聯合

[英]Select union in a Stored Procedure

我使用postgresql創建了此存儲過程:

 create or replace Function GetTimeStamp(
    IN t1 timestamp ,
    IN t2 timestamp ,
    Out reg_os Varchar(50),
    Out customer_count int ,
    Out t5 timestamp
    ) returns void AS $$
    Begin

    SELECT payment.payment_ts AS t , customer.registration_os As os ,count(Distinct customer.customer_id) As total
    From customer inner join payment on customer.customer_id = payment.customer_id
    Where Payment.payment_ts Between t1 And t2 
    Group By 1 , 2
    Union
    SELECT transfer.ts_created AS t , customer.registration_os As os, count(Distinct customer.customer_id) As total 
    From customer inner join account on customer.customer_id = account.customer_id inner join transfer on account.account_id = transfer.from_account
    Where transfer.ts_created Between t1 And t2 
    Group By 1 , 2;
    select t , os , total into t5 , reg_os , customer_count ;
    End;
    $$ LANGUAGE plpgsql;

我可以創建存儲過程,但是當我使用以下代碼時:

 SELECT GetTimeStamp('2016-01-01' ,'2017-01-01')   OR  
 SELECT * FROM GetTimeStamp('2016-01-01' ,'2017-01-01')

它給我一個錯誤:

查詢沒有結果數據的目標提示:如果要舍棄SELECT的結果,請改用PERFORM

我在存儲過程中使用了表演而不是選擇,它給了我

PERFORM附近的語法錯誤。

我不知道是否可以在兩個執行查詢之間使用聯合。如何獲取此存儲過程的結果?

在PL / pgSQL中,您需要使用SELECT ... INTO來指定應將結果存儲在其中的變量。 要舍棄結果,請使用PERFORM而不是SELECT

您需要返回一個集合( table ,它可以是純SQL

create or replace Function GetTimeStamp (
   IN t1 timestamp ,
   IN t2 timestamp
) returns table (
    reg_os Varchar(50),
    customer_count int,
    t5 timestamp
) language sql as $$

    SELECT
        payment.payment_ts AS t ,
        customer.registration_os As os ,
        count(Distinct customer.customer_id) As total
    From
        customer
        inner join
        payment on customer.customer_id = payment.customer_id
    Where Payment.payment_ts Between t1 And t2 
    Group By 1 , 2

    Union

    SELECT
        transfer.ts_created AS t ,
        customer.registration_os As os,
        count(Distinct customer.customer_id) As total 
    From
        customer
        inner join
        account on customer.customer_id = account.customer_id
        inner join
        transfer on account.account_id = transfer.from_account
    Where transfer.ts_created Between t1 And t2 
    Group By 1 , 2;
$$;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM