从Sql Server转战Oracle 之 变量声明

 1 --两种声明方法:没有sql所谓的select或者select @para from table 以及 set 赋值,且赋值的时候需要在begin end事务内
 2 一 直接声明
 3 declare str varchar2(256)   --变量不加@,直接定义类型
 4 begin 
 5 select 'asd' into str from dual;--通过into赋值,如果有多个变量时,按照顺序赋值select 'asd' ,'a','s'into str,str1,str2 from dual;
 6 dbms_output.put_line(str); --输出结果为asd  
7
end
8


1 create table a 
2 (
3 name varchar2(256)
4 ,id varchar2(256)
5 )
6 
7 insert into a
8 values('asd','1')
创建测试表
二 利用%type 或%rowtype 声明
declare str table.id%type   --未知变量类型时,利用%type定义目标表字段的类型
 begin 
 select id into str from a where id=1;
 dbms_output.put_line(str);--结果  1
 end;
 
 
 
 --注意这里的关键字是%rowtype
declare str a%rowtype ; --也可以利用第二种的方式,直接定义目标表的类型, begin select * into str from a where id=1;--直接取表中其中一列赋值 dbms_output.put_line('str.name='||str.name||' str.id='||str.id);--结果 str.name=asd str.id=1
end;

赋值方法除利用select value into 进行赋值外,类似sql的set @a=(select count(1)from table)的赋值如下

declare str  varchar2(256);
 sq varchar2(256);
begin 
--select id into str from a where id=1;
sq :='select id  from a where id=1';
execute immediate sq  into str;  --即通过动态sql进行赋值
dbms_output.put_line(str);
end;

在存储过程中声明变量时

转载请注明出处!

参考:https://www.cnblogs.com/Marydon20170307/p/9567493.html

立刻行动,坚持不懈,不断学习!
原文地址:https://www.cnblogs.com/deng779256146/p/13361395.html