PostgreSQL存储过程中变量&常量

PostgreSQL存储过程中变量

declare variable_name data_type [:=expression]; #declare关键字声明变量

案例1:
do $$
declare 
        counter integer :=1;
        first_name varchar(50) := 'John';
        last_name varchar(50) := 'Doe';
        payment numeric(11,2) := 20.5;
begin
        
    raise notice '% % % has been paid % usd',counter,first_name,last_name,payment;
end $$;

结果:
1 John Doe has been paid 20.50 usd




案例2:
do $$
declare 
    create_time time := now();
begin

    raise notice '%',create_time;
    perform pg_sleep(10);
    raise notice '%',create_time;
end $$;

结果:虽然中间休眠了10秒,但是变量create_time的赋值在之前声明时已经固定了,所以没有再次被声明修改时,是不改变其值的
21:05:54.774563
21:05:54.774563




案例3:
赋值其它表的列的数据类型,这样就不用自己定义类型,当其它的表列的类型改变时随之改变
declare 变量名  表名.列名%TYPE := 赋值;


do $$
declare 
     city_name city.city%TYPE :='hudechao';
begin
    raise notice '%',city_name;

end $$;
结果:
hudechao


案例4:
为变量名命名一个别名
new_name alias for old_name;

do $$
declare 
     city_name city.city%TYPE :='hudechao';
     new_city alias for city_name;
begin
    raise notice '%',new_city;

end $$;
结果:
hudechao

PostgreSQL中的常量

语法:
declare 常量名 constant 类型 := 赋值; #constant为关键字声明为常量

案列1:
do $$
declare 
    vat constant numeric := 0.1;
    net_price numeric := 20.5;

begin
    
    raise notice 'the selling price is %' ,net_price*(1+vat);
end $$;
结果:
> 注意:  the selling price is 22.55


案例2:
do $$
declare 
    vat constant numeric := 0.1;
    net_price numeric := 20.5;

begin
    
    raise notice 'the selling price is %' ,net_price*(1+vat);
    vat := vat+1;
end $$;
结果:由结果得知,变量再被声明后是不能再被修改的。
> 错误:  变量"vat"被声明为常量
LINE 9:  vat := vat+1;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容