sqlplus模式下:
var 變量名 變量類型;
例如:
var name varchar2(50);
select name into :name from t_user;
select :name from dual;
切換用戶后仍有效,斷開sqlplus后無效;
declare聲明變量和賦值:
declare
name varchar2(50):='小明';
begin
dbms_output.put_line(name);
end
/
錨定(將變量類型與表中字段類型綁定):
declare
user_code t_user.user_code%type;
user_name t_user.user_name%type;
user_birth_day date;
begin
select user_code,user_name,user_birth_day into user_code,user_name,user_birth_day from t_user where user_code=121;
dbms_output.put_line(user_name);
end
/
復合變量:
declare
type user_record is record
(user_code number,
user_name varchar2(50),
user_birth_day date)
rc user_record;
begin
select * into rc from t_user where user_code=101;
dbms_output.put_line(rc.user_name);
end;
/
使用%后:
declare
rc t_user%rowtype;
begin
select * into rc from t_user where user_code=101;
dbms_output.put_line(rc.user_name);
end;
/
游標變量:
聲明:初始化游標變量標示符,將游標變量標示符和一個子查詢關聯在一起
打開:根據子查詢取數據庫表中的數據填充內存上下文
獲取:從游標內存上下文取值填充到record,游標內存上下文中的值每取出一行就丟棄一行
關閉:將游標內存上下文釋放
游標屬性:
游標名字%rowcount : 從游標內存上下文獲得的行的數量
游標名字%found : 從游標內存上下文獲得了返回true
游標名字%notfound : 從游標內存上下文取不到數據返回true
游標名字%isopen : 游標如果打開返回true
declare
cursor cs is select * fromn t_user; --聲明
rc cs%rowtype;
begin
open cs; --打開
loop
fetch cs into rc; --獲取
exit when cs%notfound;
dbms_output.put_line(rc.user_name);
end loop;
close cs; --關閉
end;
/
游標for循環(隱式聲明、打開、獲取、關閉):
declare
cursor cs is select * fromn t_user; --聲明,可省略
begin
for rc in cs loop --cs可以直接使用子查詢代替(select * fromn t_user)
dbms_output.put_line(rc.user_name);
end loop;
end;
/
帶參數的游標:
declare
cursor cs (t_usercode number) is select user_code,user_name,user_birth_day from t_user where user_code=t_usercode order by user_birth_day desc;
begin
for rc in cs (2) loop
dbms_output.put_line(rc.user_code||'--'||rc.user_name||'--'||rc.user_birth_day);
end loop;
end;
/
:變量名是plsql外部變量使用方式,plsql內部變量直接使用即可