zoukankan      html  css  js  c++  java
  • PostgreSQL function examples

    warehouse_db=# CREATE TABLE warehouse_tbl
    (
    warehouse_id INTEGER NOT NULL,
    warehouse_name TEXT NOT NULL,
    year_created INTEGER,
    street_address TEXT,
    city CHARACTER VARYING(100),
    state CHARACTER VARYING(2),
    zip CHARACTER VARYING(10),
    CONSTRAINT "PRIM_KEY" PRIMARY KEY (warehouse_id)
    );

    CREATE TABLE history
    (
    history_id INTEGER NOT NULL DEFAULT nextval('hist_id_seq'),
    date TIMESTAMP WITHOUT TIME ZONE,
    amount INTEGER,
    data TEXT,
    customer_id INTEGER,
    warehouse_id INTEGER,
    CONSTRAINT "PRM_KEY" PRIMARY KEY (history_id),
    CONSTRAINT "FORN_KEY"
    FOREIGN KEY (warehouse_id)
    REFERENCES warehouse_tb1(warehouse_id)
    );

    warehouse_db=# d warehouse_tb1
    Table "public.warehouse_tb1"
    Column | Type | Modifiers
    ----------------+------------------------+-----------
    warehouse_id | integer | not null
    warehouse_name | text | not null
    year_created | integer |
    street_address | text |
    city | character varying(100) |
    state | character varying(2) |
    zip | character varying(10) |
    Indexes:
    "PRIM_KEY" PRIMARY KEY, btree (warehouse_id), tablespace "tbs_yl"
    Referenced by:
    TABLE "history" CONSTRAINT "FORN_KEY" FOREIGN KEY (warehouse_id) REFERENCES warehouse_tb1(warehouse_id)
    Tablespace: "tbs_yl"


    warehouse_db=# alter table warehouse_tb1 add column phone_no integer;
    ALTER TABLE
    warehouse_db=# d warehouse_tb1
    Table "public.warehouse_tb1"
    Column | Type | Modifiers
    ----------------+------------------------+-----------
    warehouse_id | integer | not null
    warehouse_name | text | not null
    year_created | integer |
    street_address | text |
    city | character varying(100) |
    state | character varying(2) |
    zip | character varying(10) |
    phone_no | integer |
    Indexes:
    "PRIM_KEY" PRIMARY KEY, btree (warehouse_id), tablespace "tbs_yl"
    Referenced by:
    TABLE "history" CONSTRAINT "FORN_KEY" FOREIGN KEY (warehouse_id) REFERENCES warehouse_tb1(warehouse_id)
    Tablespace: "tbs_yl"

    warehouse_db=# alter table warehouse_tb1 drop column phone_no;
    ALTER TABLE
    warehouse_db=# d warehouse_tb1
    Table "public.warehouse_tb1"
    Column | Type | Modifiers
    ----------------+------------------------+-----------
    warehouse_id | integer | not null
    warehouse_name | text | not null
    year_created | integer |
    street_address | text |
    city | character varying(100) |
    state | character varying(2) |
    zip | character varying(10) |
    Indexes:
    "PRIM_KEY" PRIMARY KEY, btree (warehouse_id), tablespace "tbs_yl"
    Referenced by:
    TABLE "history" CONSTRAINT "FORN_KEY" FOREIGN KEY (warehouse_id) REFERENCES warehouse_tb1(warehouse_id)
    Tablespace: "tbs_yl"

    warehouse_db=# insert into warehouse_tb1(warehouse_id,warehouse_name,year_created,street_address,city,state,zip) values (1,'Mark Corp',2009,'207-F Main Service Road Ease','New London','CT',4321);
    INSERT 0 1
    warehouse_db=# select warehouse_id,warehouse_name,street_address from warehouse_tb1;
    warehouse_id | warehouse_name | street_address
    --------------+----------------+------------------------------
    1 | Mark Corp | 207-F Main Service Road Ease
    (1 row)
    warehouse_db=# update warehouse_tb1 set year_created=2010 where year_created=2009;
    UPDATE 1
    warehouse_db=# select warehouse_id,year_created from warehouse_tb1;
    warehouse_id | year_created
    --------------+--------------
    1 | 2010
    (1 row)
    warehouse_db=# insert into warehouse_tb1(warehouse_id,warehouse_name,year_created,street_address,city,state,zip)
    warehouse_db-# values (2,'Bill & Co',2014,'Lilly Road','New London','CT',4321);
    INSERT 0 1
    warehouse_db=# insert into warehouse_tb1(warehouse_id,warehouse_name,year_created,street_address,city,state,zip)
    warehouse_db-# values (3,'West point',2013,'Down Town','New London','CT',4321);
    INSERT 0 1
    warehouse_db=# select warehouse_id,warehouse_name,street_address from warehouse_tb1;
    warehouse_id | warehouse_name | street_address
    --------------+----------------+------------------------------
    1 | Mark Corp | 207-F Main Service Road Ease
    2 | Bill & Co | Lilly Road
    3 | West point | Down Town
    (3 rows)
    warehouse_db=# delete from warehouse_tb1 where warehouse_name='Bill & Co';
    DELETE 1
    warehouse_db=# select warehouse_id,warehouse_name,street_address from warehouse_tb1;
    warehouse_id | warehouse_name | street_address
    --------------+----------------+------------------------------
    1 | Mark Corp | 207-F Main Service Road Ease
    3 | West point | Down Town
    (2 rows)
    warehouse_db=# create table tools(tool_id integer unique,too_name text,tool_class numeric);
    CREATE TABLE
    warehouse_db=# create table mytools(tool_id integer,tool_name text,tool_class numeric,unique(tool_id));
    CREATE TABLE
    warehouse_db=#
    warehouse_db=# create table cards(card_id integer,owner_number integer,owner_name text,unique(card_id,owner_number));
    CREATE TABLE
    warehouse_db=# create table tools(tool_id integer not null,tool_name text,tool_class numeric);
    CREATE TABLE
    warehouse_db=# create table mytools(tool_id integer not null,tool_name text not null,tool_class numeric);
    CREATE TABLE
    warehouse_db=# create table tools(tool_id integer primary key,tool_name text,tool_class numeric);
    CREATE TABLE
    warehouse_db=# create table mytools(tool_id integer ,tool_name text,tool_class numeric,primary key(tool_id,tool_name));
    CREATE TABLE
    warehouse_db=# d+ tools
    Table "public.tools"
    Column | Type | Modifiers | Storage | Stats target | Description
    ------------+---------+-----------+----------+--------------+-------------
    tool_id | integer | not null | plain | |
    tool_name | text | | extended | |
    tool_class | numeric | | main | |
    Indexes:
    "tools_pkey" PRIMARY KEY, btree (tool_id), tablespace "tbs_yl"
    Tablespace: "tbs_yl"

    warehouse_db=# d+ mytools
    Table "public.mytools"
    Column | Type | Modifiers | Storage | Stats target | Description
    ------------+---------+-----------+----------+--------------+-------------
    tool_id | integer | not null | plain | |
    tool_name | text | not null | extended | |
    tool_class | numeric | | main | |
    Indexes:
    "mytools_pkey" PRIMARY KEY, btree (tool_id, tool_name), tablespace "tbs_yl"
    Tablespace: "tbs_yl"

    warehouse_db=# create table tools(tool_id integer primary key,tool_name text,tool_class numeric);
    CREATE TABLE
    warehouse_db=# create table tools_list(list_id integer primary key,tool_id integer references tools (tool_id),list_name text);
    CREATE TABLE
    warehouse_db=# d+ tools
    Table "public.tools"
    Column | Type | Modifiers | Storage | Stats target | Description
    ------------+---------+-----------+----------+--------------+-------------
    tool_id | integer | not null | plain | |
    tool_name | text | | extended | |
    tool_class | numeric | | main | |
    Indexes:
    "tools_pkey" PRIMARY KEY, btree (tool_id), tablespace "tbs_yl"
    Referenced by:
    TABLE "tools_list" CONSTRAINT "tools_list_tool_id_fkey" FOREIGN KEY (tool_id) REFERENCES tools(tool_id)
    Tablespace: "tbs_yl"

    warehouse_db=# d+ mytools
    Did not find any relation named "mytools".
    warehouse_db=# d+ tools_list
    Table "public.tools_list"
    Column | Type | Modifiers | Storage | Stats target | Description
    -----------+---------+-----------+----------+--------------+-------------
    list_id | integer | not null | plain | |
    tool_id | integer | | plain | |
    list_name | text | | extended | |
    Indexes:
    "tools_list_pkey" PRIMARY KEY, btree (list_id), tablespace "tbs_yl"
    Foreign-key constraints:
    "tools_list_tool_id_fkey" FOREIGN KEY (tool_id) REFERENCES tools(tool_id)
    Tablespace: "tbs_yl"

    CREATE OR REPLACE FUNCTION func_declare()
    RETURNS text AS $$
    DECLARE --Variable store declared not null with a default value.
    nanvar VARCHAR NOT NULL := 'notnull text';--Declaring an integer to hold integer constant.
    digit CONSTANT INTEGER := 10;
    /* declaring variable with
    a default value.*/
    helloworld VARCHAR DEFAULT 'PostgreSQL rocks !';
    BEGIN
    RETURN nanvar;
    END;
    $$ LANGUAGE 'plpgsql';

    CREATE OR REPLACE FUNCTION func_declarell()
    RETURNS text AS $$
    DECLARE --Variable store declared not null with a default value.
    nanvar VARCHAR NOT NULL := 'notnull text';--Declaring an integer to hold integer constant.
    digit CONSTANT INTEGER := 10;
    /* declaring variable with
    a default value.*/
    helloworld VARCHAR DEFAULT 'PostgreSQL rocks !';
    BEGIN
    RETURN nanvar;
    END;
    $$ LANGUAGE 'plpgsql';

    CREATE OR REPLACE FUNCTION func_declarell()
    RETURNS text AS $$
    DECLARE --Variable store declared not null with a default value.
    nanvar VARCHAR NOT NULL := 'notnull text';--Declaring an integer to hold integer constant.
    digit CONSTANT INTEGER := 10;
    /* declaring variable with
    a default value.*/
    helloworld VARCHAR DEFAULT 'PostgreSQL rocks !';
    BEGIN
    RETURN digit;
    END;
    $$ LANGUAGE 'plpgsql';

    warehouse_db=# create or replace function alias_explain(int)
    returns integer as $$
    declare
    total alias for $1;
    begin
    return total*10;
    end;
    $$ language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select alias_explain(10);
    alias_explain
    ---------------
    100
    (1 row)

    warehouse_db=# create or replace function alias_explain(int)
    warehouse_db-# returns integer as $$
    warehouse_db$# begin
    warehouse_db$# return $1 * 10;
    warehouse_db$# end;
    warehouse_db$# $$language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select alias_explain(10);
    alias_explain
    ---------------
    100
    (1 row)

    warehouse_db=# create or replace function alias_explain(total int)
    warehouse_db-# returns integer as $$
    warehouse_db$# begin
    warehouse_db$# return total * 10;
    warehouse_db$# end;
    warehouse_db$# $$language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select alias_explain(10);
    alias_explain
    ---------------
    100
    (1 row)

    warehouse_db=# create or replace function func_param(a int,IN b int,OUT plus int,OUT sub int)as $$
    warehouse_db$# begin
    warehouse_db$# plus :=a +b;
    warehouse_db$# sub :=a-b;
    warehouse_db$# end;
    warehouse_db$# $$language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select func_param(10,5);
    func_param
    ------------
    (15,5)
    (1 row)
    warehouse_db=# create or replace function simple_loop(subjects integer) returns integer as $$
    warehouse_db$# declare
    warehouse_db$# grade integer := 10;
    warehouse_db$# begin
    warehouse_db$# loop
    warehouse_db$# grade := grade * subjects;
    warehouse_db$# if (grade >= 100) then
    warehouse_db$# exit;
    warehouse_db$# end if;
    warehouse_db$# end loop;
    warehouse_db$# return grade;
    warehouse_db$# end;
    warehouse_db$# $$language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select simple_loop(10);
    simple_loop
    -------------
    100
    (1 row)
    warehouse_db=# create or replace function while_loop(subjects integer) returns integer as $$
    declare
    grade integer := 10;
    begin
    while grade <=100
    loop
    grade := grade * subjects;
    end loop;
    return grade;
    end;
    $$language plpgsql;
    CREATE FUNCTION
    warehouse_db=#
    warehouse_db=# select while_loop(5);
    while_loop
    ------------
    250
    (1 row)


    warehouse_db=# create or replace function first_for_loop(subjects integer) returns integer as $$
    warehouse_db$# declare
    warehouse_db$# grade integer :=2;
    warehouse_db$# begin
    warehouse_db$# for i in 1..10
    warehouse_db$# loop
    warehouse_db$# grade := grade * subjects;
    warehouse_db$# end loop;
    warehouse_db$# return grade;
    warehouse_db$# end;
    warehouse_db$# $$ language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select first_for_loop(2);
    first_for_loop
    ----------------
    2048
    (1 row)
    warehouse_db=# create or replace function second_for_loop(subjects integer) returns integer as $$
    warehouse_db$# declare
    warehouse_db$# grade integer :=2;
    warehouse_db$# begin
    warehouse_db$# for i in reverse 10..1 by 2
    warehouse_db$# loop
    warehouse_db$# grade := grade * subjects;
    warehouse_db$# end loop;
    warehouse_db$# return grade;
    warehouse_db$# end;
    warehouse_db$# $$ language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select second_for_loop(2);
    second_for_loop
    -----------------
    64
    (1 row)

    warehouse_db=# create or replace function for_loop_query(query varchar) returns integer as $$
    warehouse_db$# declare
    warehouse_db$# count integer := 0;
    warehouse_db$# table_records record;
    warehouse_db$# begin
    warehouse_db$# for table_records in execute query
    warehouse_db$# loop
    warehouse_db$# count := count +1;
    warehouse_db$# end loop;
    warehouse_db$# return count;
    warehouse_db$# end;
    warehouse_db$# $$language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select for_loop_query('select * from warehouse_tb1');
    for_loop_query
    ----------------
    2
    (1 row)

    warehouse_db=# select * from warehouse_tb1;
    warehouse_id | warehouse_name | year_created | street_address | city | state | zip
    --------------+----------------+--------------+------------------------------+------------+-------+------
    1 | Mark Corp | 2010 | 207-F Main Service Road Ease | New London | CT | 4321
    3 | West point | 2013 | Down Town | New London | CT | 4321
    (2 rows)


    warehouse_db=# create or replace function how_to_raise() returns integer as $$
    warehouse_db$# declare
    warehouse_db$# total integer;
    warehouse_db$# begin
    warehouse_db$# select count(*) into total from warehouse_tb1;
    warehouse_db$# if (total > 0) then
    warehouse_db$# return total;
    warehouse_db$# else
    warehouse_db$# raise notice 'table is empty,%,rows',total;
    warehouse_db$# end if;
    warehouse_db$# end;
    warehouse_db$# $$language plpgsql;
    CREATE FUNCTION
    warehouse_db=# select how_to_raise();
    how_to_raise
    --------------
    2
    (1 row)

    warehouse_db=# delete from warehouse_tb1 ;
    DELETE 2
    warehouse_db=# select how_to_raise();
    NOTICE: table is empty,0,rows
    ERROR: control reached end of function without RETURN
    CONTEXT: PL/pgSQL function how_to_raise()
    warehouse_db=#

    warehouse_db=# create or replace function test_sqlerrm( ) returns integer as $$
    declare
    var int :=0;
    begin
    raise notice 'hello %','1234';
    var :=(select 1 + 1 );
    return var;
    end;
    $$language plpgsql;
    CREATE FUNCTION
    Time: 6.290 ms
    warehouse_db=# select test_sqlerrm();
    NOTICE: hello 1234
    -[ RECORD 1 ]+--
    test_sqlerrm | 2

    Time: 1.042 ms
    warehouse_db=# x
    Expanded display is off.
    warehouse_db=# select test_sqlerrm();
    NOTICE: hello 1234
    test_sqlerrm
    --------------
    2
    (1 row)

    Time: 1.160 ms

    warehouse_db=# create table accounts(owner text,balance numeric);
    CREATE TABLE
    warehouse_db=# insert into accounts values ('Bob',100);
    INSERT 0 1
    warehouse_db=# insert into accounts values ('Mary',200);
    INSERT 0 1
    warehouse_db=# update accounts set balance = balance - 14.00 where owner = 'Bob';
    UPDATE 1
    warehouse_db=# update accounts set balance = balance + 14.00 where owner = 'Mary';
    UPDATE 1

    warehouse_db=# CREATE OR REPLACE FUNCTION transfer(
    warehouse_db(# i_payer text,
    warehouse_db(# i_recipient text,
    warehouse_db(# i_amount numeric(15,2))
    warehouse_db-# RETURNS text
    warehouse_db-# AS
    warehouse_db-# $$
    warehouse_db$# DECLARE
    warehouse_db$# payer_bal numeric;
    warehouse_db$# BEGIN
    warehouse_db$# SELECT balance INTO payer_bal
    warehouse_db$# FROM accounts
    warehouse_db$# WHERE owner = i_payer FOR UPDATE;
    warehouse_db$# IF NOT FOUND THEN
    warehouse_db$# RETURN 'Payer account not found';
    warehouse_db$# END IF;
    warehouse_db$# IF payer_bal < i_amount THEN
    warehouse_db$# RETURN 'Not enough funds';
    warehouse_db$# END IF;
    warehouse_db$# UPDATE accounts
    warehouse_db$# SET balance = balance + i_amount
    warehouse_db$# WHERE owner = i_recipient;
    warehouse_db$# IF NOT FOUND THEN
    warehouse_db$# RETURN 'Recipient does not exist';
    warehouse_db$# END IF;
    warehouse_db$# UPDATE accounts
    warehouse_db$# SET balance = balance - i_amount
    warehouse_db$# WHERE owner = i_payer;
    warehouse_db$# RETURN 'OK';
    warehouse_db$# END;
    warehouse_db$# $$ LANGUAGE plpgsql;
    CREATE FUNCTION
    warehouse_db=# select * from accounts ;
    owner | balance
    -------+---------
    Bob | 86.00
    Mary | 214.00
    (2 rows)

    warehouse_db=# select * from transfer('Bob','Mary',14.00);
    transfer
    ----------
    OK
    (1 row)

    warehouse_db=# select * from accounts ;
    owner | balance
    -------+---------
    Mary | 228.00
    Bob | 72.00
    (2 rows)

    warehouse_db=# select * from transfer('Fred','Mary',14.00);
    transfer
    -------------------------
    Payer account not found
    (1 row)

    warehouse_db=# select * from transfer('Bob','Fred',14.00);
    transfer
    --------------------------
    Recipient does not exist
    (1 row)

    warehouse_db=# select * from transfer('Bob','Mary',500.00);
    transfer
    ------------------
    Not enough funds
    (1 row)

  • 相关阅读:
    圆周率的计算与进度条
    Python的使用方法
    Python科学计算库
    linux 命令总结[转]
    如何在 Windows 平台上下載 Android 的源码[转]
    装MSN报错问题解决 无法定位程序输入点except handler4 common 于动态链接库nsvcrt.dll【转】
    编写xorg.conf,简单三行解决ubuntu分辩率不可调的问题【转】
    谁说 Android 手机一定要 root 权限才能截屏?![转]
    给自己的忠告[转]
    lockdir加密bug[转]
  • 原文地址:https://www.cnblogs.com/songyuejie/p/4877796.html
Copyright © 2011-2022 走看看