Oracle PL/SQL 变量

本文介绍PL/SQL中变量的声明与初始化方法,包括基本数据类型、复合数据类型及如何利用%type和%rowtype简化变量声明过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基础变量

类型标示符 [not null] := 值;

declare 
    age number(3):=26; 
    price number(8,2) := 876.21; 
    c number(6) := 0;
    -- 也可以不用输入后面的具体值 c number(6)
begin 
    select count(*) into c from testTable ;
        dbms_output.put_line(‘总条数:’ || c);
    commit ; 
end ; 

变量的初始化:      

Declare             
    v_numberseats  number:=45;             
    v_counter  int:=0; 

-- 注意:后面跟“:=” 来向声明语句中的变量来指定初始值。也可以使用default替代:=符号。       
Declare             
    v_numberseat number default 45;

变量初始化 NOT NULL和CONSTANT

常量名 constant 类型标示符 [not null] :=值;

declare  
    C_minimunstudentid  constant number(5):=10000;
   
    -- 如果变量在声明时使用了constant,则该变量应被初始化,且以后不能改变它的值。
    -- 如果在声明时指明not null,那么应该给该变量赋初值,下面声明是错误的:
    Declare
        v_tempvar  number   not null;
    
    --正确的声明为:
    Declare
        v_tempvar   number   not null:=1;

注意:CONSTANT关键字是在变量类型之前列出的,而NOT NULL是在数据类型之后列出的。

%type 定义变量

PL/SQL 使用中可能会遇到变量值的类型要跟表中的某个字段保持一致,但如果表中的类型变了,那么 PL/SQL 也需要变化,会很麻烦,所以使用 "%type" 进行变量声明

declare 
    -- mydate 参照表 testtable 中的字段 tDate 的类型
    mydate testtable.tDate%type; 
begin 
    select tdate into mydate from testTable where tid=1;
    dbms_output.put_line(mydate); 
end ; 

记录类型

复合数据类型变量(record)

参考java中的类,PL/SQL 还有一种定义数据的方式

declare
    type myRecord is record( -- record 相当于 class的声明, myRecord 是类名
        myId int, 
        myDate date, 
        myTitle varchar2(15) 
    ); 
    row myRecord; -- 声明row 是myRecord类型的变量

begin 
    select * into row from testtable where tId=1; 
    dbms_output.put_line(row.myDate||’,’|| row.myTitle); 
end;

%rowtype 声明记录

自动获取表中的整行数据

declare 
    row testTable%rowtype; -- row 为变量名 testTable 为表名 %rowtype 
begin 
    select * into row from testTable where tId=68 ; 
    dbms_output.put_line(row.tDate||’,’|| row.title); -- 此时要使用
end ; 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值