日期:2014-05-17  浏览次数:20867 次

declare,if简单常识求教
--主要是想检查,学生表里是否有数据,如果有显示,没有的话加一条,但是我这里语句报错,求大家帮看看
--我用的pl/sql,如果直接执行下面的会报错,是我需要设置什么还是我写的有错呢?

declare  
int_Count   number(10);

begin
select   count(pkid)   into   int_Count   from   students;  
if   int_Count> 0   then
  select   *   from     students
else
  INSERT   INTO   students   VALUES   ( '小明 ')
end   if;
end   begin

------解决方案--------------------
declare
int_Count number(10);

begin
select count(pkid) into int_Count from students;
select * from students(不过这里如果要返回一个数据集,不能这么写,呵呵,懒得弄了,默认楼主是为了简化才这么表示)
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO students VALUES ( '小明 ');
end begin

------解决方案--------------------
declare
int_Count number(10);
cursor cur;
fname varchar2(100);
begin
select count(pkid) into int_Count from students;
if int_Count> 0 then
open cur for select name from students;
loop
fetch cur into fname;
exit when cur%notfound;
dbms_output.put_line( fname );
end loop;
close cur;
else
INSERT INTO students VALUES ( '小明 ')
end if;
end;
------解决方案--------------------
declare
int_Count number(10);

begin
select count(pkid) into int_Count from students;
if int_Count> 0 then
select * from students
else
INSERT INTO students VALUES ( '小明 ')
end if;
end begin


if(exists(select pkid into int_Count from students; )) then
select * from students
else
INSERT INTO students VALUES ( '小明 ')
end if;

------解决方案--------------------
用了select 就要用into将变量值放在数据库里
------解决方案--------------------
select * from students; pl/sql中不能返回数据集;
若数据表中不只一个字段,则应指明需要插入数据的字段