首页 > 解决方案 > 查找所有相关表中是否存在数据 (PL/SQL)

问题描述

我正在寻找一种方法来查找所有相关表中是否存在数据。(ID_HOUSE = 1) 查找所有 ID_HOUSE 列中是否存在 1。

Table House    Table Bedrooms   Table Garden    and more...
ID_HOUSE       ID_HOUSE (F)     ID_HOUSE (F)
               ID_BEDR          ID_GARDEN

ID_HOUSE = 号码;我想知道他的相关表中是否存在 ID 为 455 的 ID_HOUSE。例如:

Table House    
ID_HOUSE = 455; 
exists in ID_HOUSE(table bedrooms) or ID_HOUSE(table garden) and more...???
OUTPUT: true/false  (exists in any other related tables or not)

我的第一个想法是“SELECT CASE WHEN COUNT 并加入 WHERE ID_HOUSE = 1”,但我不知道该怎么做有什么帮助吗?

标签: sqlplsql

解决方案


前段时间我这样做是为了找到所有相关的表,也许可以帮助你:

declare
  --
  v_exist varchar2(1);
  --
begin
  --
  for reg in (select distinct table_name
              from all_constraints
              where upper(r_owner) = upper(&owner)
              and constraint_type = 'R'
              and r_constraint_name in (select constraint_name
                                        from all_constraints
                                        where constraint_type in ('P', 'U')
                                        and upper(table_name) = upper(&origin_table)
                                        and upper(owner) = upper(&owner))
              order by table_name)
  loop
    --
    v_exist := null;
    --
    begin
      --
      execute immediate 'select 1 from ' || reg.table_name || ' ' || &v_where into v_exist;
      --
      if v_exist is not null then
        dbms_output.put_line(reg.table_name);      
      end if;
      --
    exception
      when NO_DATA_FOUND then
        null;
      when TOO_MANY_ROWS then
        dbms_output.put_line(reg.table_name);
      when others then
        dbms_output.put_line('Table ' || reg.table_name || '; error: ' || sqlerrm);
    end;
    --
  end loop;
  --
end;

推荐阅读