PLのselect intoの挙動

(5.6)

-- 確認事項
データが0件、2件の場合のPLでのselect intoの挙動

-- テストデータ準備

drop table tab1;
create table tab1(col1 int);
insert into tab1 values(1);
insert into tab1 values(2);
insert into tab1 values(2);

select * from tab1;

-- 挙動確認

drop procedure proc1;

delimiter //
create procedure proc1(in p1 integer)
begin
declare i int;
set i = 99;
select col1 into i from tab1 where col1 = p1;
end
//
delimiter ;

call proc1(0);
→警告終了(No data - zero rows fetched, selected, or processed)

call proc1(1);
→正常終了

call proc1(2);
→異常終了(ERROR 1172 (42000): Result consisted of more than one row)

(12cR1)

-- 確認事項
データが0件、2件の場合のPLでのselect intoの挙動

-- テストデータ準備

drop table tab1 purge;
create table tab1(col1 int);
insert into tab1 values(1);
insert into tab1 values(2);
insert into tab1 values(2);
commit;
select * from tab1;


-- 挙動確認

set serveroutput on
create or replace procedure proc1(p1 in integer) as
i integer;
begin
i := 99;
select col1 into i from tab1 where col1 = p1;
dbms_output.put_line('i=' || to_char(i) );
end;
/

exec proc1(0);
→異常終了(ORA-01403: データが見つかりません。)

exec proc1(1);
→正常終了

exec proc1(2);
→異常終了(ORA-01422: 完全フェッチがリクエストよりも多くの行を戻しました)

 

https://www.postgresql.jp/document/13/html/plpgsql-statements.html#PLPGSQL-STATEMENTS-ASSIGNMENT

(14)

-- 確認事項
データが0件、2件の場合のPLでのselect intoの挙動

-- テストデータ準備

drop table tab1;
create table tab1(col1 int);
insert into tab1 values(1);
insert into tab1 values(2);
insert into tab1 values(2);

select * from tab1;


-- 挙動確認

create or replace function fun1(in p1 integer) returns integer
as
$$
declare
i integer;
begin
i := 99;
select col1 into i from tab1 where col1 = p1;
raise info '%', i;
return i;
end;
$$ language 'plpgsql';


select fun1(0);
→正常終了(戻り値はNULL)

select fun1(1);
→正常終了

select fun1(2);
→正常終了(戻り値は2)


※データがない場合にエラーを発生させたい場合は、STRICT オプションを使用する

create or replace function fun2(in p1 integer) returns integer
as
$$
declare
i integer;
begin
i := 99;
select col1 into STRICT i from tab1 where col1 = p1;
raise info '%', i;
return i;
end;
$$ language 'plpgsql';

select fun2(0);
→ERROR:  query returned no rows

select fun2(1);
→正常終了

select fun2(2);
→ERROR:  query returned more than one row

 

 

 

 

 

(2014)

-- 確認事項
データが0件、2件の場合のPLでのselect intoの挙動

-- テストデータ準備

drop table tab1;
create table tab1(col1 int);
insert into tab1 values(1);
insert into tab1 values(2);
insert into tab1 values(2);

select * from tab1;


-- 挙動確認

drop procedure proc1;
go
create procedure proc1(@p1 integer)
as
begin
declare @i integer;
set @i = 99;
set @i = (select col1 from tab1 where col1 = @p1);
print '@i=' + ISNULL( convert(varchar,@i), 'NULL');
end
go

exec proc1 0;
→正常終了(戻り値はNULL)

exec proc1 1;
→正常終了

exec proc1 2;
→異常終了(サブクエリは複数の値を返しました。)