Oracle PL/SQL 变量

基础变量

类型标示符 [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 ; 

你可能感兴趣的:(oracle,sql)