sql语句在plsql中的运用

一. DML语句

–数据操纵语句

​ TCL语句–事务控制语句
–可以直接在plsql块中使用的语句

1
2
3
4
5
6
begin
insert into empa(ename,sal) values ('朱精卫',3000);
commit;
end;
/
select * from empa;

二. DDL语句

–数据定义语句

–不能直接在plsql块中使用

execute immediate –可以使用字符串中的语句

execute——执行 immediate——立即

declare
v_jingwei varchar2(100);
begin
v_jingwei :=’create table yuanbo(cm number,kg number)’;
execute immediate v_jingwei;
end;

select * from yuanbo;

三. DQL语句

–数据查询语句

–不能直接在plsql块中使用
declare
v_jingwei varchar2(100);
v_emp emp%rowtype;
begin
v_jingwei :=’select * from emp where empno = 7788’;
execute immediate v_jingwei into v_emp;
dbms_output.put_line(v_emp.ename);
end;

思考题:

遇到需要字符串类型的语句时,怎么运行
declare
v_jingwei varchar2(100);
v_emp emp%rowtype;
begin
v_jingwei :=’select * from emp where ename = ‘SMITH’’;–报错
execute immediate v_jingwei into v_emp;
dbms_output.put_line(v_emp.ename);
end;

declare
v_jingwei varchar2(100);
v_emp emp%rowtype;
begin
v_jingwei :=’select * from emp where ename = ‘’SMITH’’’;–解决方法一,使用双单引号
execute immediate v_jingwei into v_emp;
dbms_output.put_line(v_emp.ename);
end;

declare
v_jingwei varchar2(100);
v_emp emp%rowtype;
begin
v_jingwei :=q’[select * from emp where ename = ‘SMITH’]’;–解决方法二,使用转义字符q’[]’
execute immediate v_jingwei into v_emp;
dbms_output.put_line(v_emp.ename);
end;
—-推荐用第二种方法