为提高效率,提问时请提供以下信息,问题描述清晰可优先响应。
【DM版本】:8
【操作系统】:Windows10
【CPU】:
【问题描述】*:从表中select 字段赋值给变量的方法。使用select ... into ,但查询结果是空时,会报数据未找到异常。
可以考虑先判断一下查询的结果是否存在,然后再select into
begin
declare t_name varchar(100);
begin
if exists(select a2 from AA.AA where a1='abc')
then
select a2 into t_name from AA.AA where a1='abc';
select t_name from dual;
end if;
end;
end;
你好
推荐解决方法是使用异常处理模块:
BEGIN
SELECT col1
INTO V_PAR1
FROM TAB1
WHERE TAB1.ID = '123456';
exception
when no_data_found then
V_PAR1 := *******;
END;
需要特别注意的一点,网上广泛介绍有一种解决此类的方法是,先用select count语句判断结果是否有数据返回,然后再执行select into语句,这个逻辑中潜藏了事务一致性上的隐患,因为select count语句和select into语句之间有可能有其他session修改数据并提交,因此该方法在金融等对数据有严格一致性要求的场景中应谨慎评估使用。
加个判断或者用set
begin
declare t_name varchar(128 char);
begin
set t_name = (select 1 from dual where 1=2);
select t_name from dual;
end;
end;