Postgres Stored Procedure cursor Function

Source: Internet
Author: User

Postgres does not support stored procedures and can only be replaced by functions.

1. The queried data is inserted into the table.

Create or replace function addcol (

Schemaname varchar,
Tablename varchar,
Colname varchar)
Returns varchar
Language 'plpgsql'
As
$
Declare
Col_name varchar;
Begin
Execute 'select column_name from information_schema.columns where table_schema = '|
Quote_literal (schemaname) | 'and table_name =' | quote_literal (tablename) | 'and column_name =' | quote_literal (colname)
Into col_name;
Raise info 'the VAL: % ', col_name;
If (col_name is null)
Then
Col_name: = colname;
Alter table meet add column membercharacter varying (128 );
Else
Col_name: = colname | 'already exist ';
End if;
Return col_name;
End;
$;
Select addcol ('Public ', 'meet', 'member ');

Drop function addcol (schemaname varchar, tablename varchar, colname varchar );

2. cursor loop record

Create or replace function add ()
Returns varchar
Language 'plpgsql'
As
$
Begin
Declare userinfo record;
Declare seq_id bigint;
Declare users refcursor;
Begin
Open users for execute 'select ID, name, email from user ';
Fetch users into userinfo;
While userinfo. ID> 0 Loop
Seq_id = nextval ('hibernate _ Sequence ');
Insert into ten (ID, name, email, type) values (seq_id, userinfo. Name, userinfo. Email, 0 );
Update rb_user Set ID = seq_id where id = userinfo. ID;
Fetch users into userinfo;
End loop;
Close users;
Return '';

End;
End
$;
-- Run
Select Add ();
Drop function add ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.