DB2/LUW SQL如何检索给定模式的所有表名,并过滤包含特定字段和值的表

toe95027  于 2022-11-07  发布在  DB2
关注(0)|答案(1)|浏览(169)

我试图查找某个模式的所有表名,这适用于以下查询:

--for DB2/LUW
select * from sysibm.systables
where CREATOR = 'SCHEMA'
and name like '%CUR%'
and type = 'T';

现在,我想再次筛选这些表,以便只获得那些包含具有特定值的特定字段的表。我已尝试通过使用游标并遍历其行来实现此目的。

begin
declare tableName varchar(255);
declare v_at_end integer default 0;
declare not_found CONDITION FOR SQLSTATE '02000';
declare c1 cursor for
    select * from sysibm.systables where CREATOR = 'SCHEMA' and name like '%CUR%' and type = 'T';
declare CONTINUE HANDLER FOR not_found SET v_at_end;

open c1;

fetch_loop:
    loop
    fetch c1 into tableName;
    if v_at_end <>0 THEN
        leave fetch_loop;
    end if;
    --how can I print current tableName? following does not work, but also doesn't throw an error I am using AQT:
    call DBMS_OUTPUT.PUT_LINE(tableName);

    --no kind of select works here, why? (SQL0104N SQLSTATE=42601)

    -- tested with:
    -- select * from SCHEMA.A_TABLE_NAME;

    -- I want to use current tableName, also doesn't work, some tries:
    -- select * from SCHEMA.:tableName where fieldName = 123456;
    -- select * from :tableName where fieldName = 123456;
    -- select name from sysibm.systables where CREATOR = 'SCHEMA' and name = :tableName and type = 'T';

end loop fetch_loop;
close c1;
end;

如何获得所有表名的表包含一个条目与一个特定的字段和值的字段?将很酷输出所有的名称在一个“控制台”或存储在一个文件中。

ezykj2lf

ezykj2lf1#

试试看:

--#SET TERMINATOR @

SET SERVEROUTPUT ON@

BEGIN
  DECLARE V_DUMMY INT;
  DECLARE V_STRING_TO_FIND VARCHAR (100) DEFAULT 'EMPLOYEE';

  FOR C1 AS
    SELECT
      C.TABSCHEMA 
    , C.TABNAME
    , 'SET ? = (SELECT 1 FROM "' 
    || C.TABSCHEMA || '"."' || C.TABNAME 
    || '" WHERE "' || C.COLNAME 
    || '" = ''' || V_STRING_TO_FIND || ''' FETCH FIRST 1 ROW ONLY)'
    AS CMD
    FROM SYSCAT.COLUMNS C
    JOIN SYSCAT.TABLES T ON (T.TABSCHEMA, T.TABNAME) = (C.TABSCHEMA, C.TABNAME) AND T.TYPE = 'T'
    WHERE C.TABSCHEMA LIKE 'SYS%' AND C.COLNAME = 'TABNAME'
  DO
    --CALL DBMS_OUTPUT.PUT_LINE (C1.CMD);
    PREPARE S1 FROM C1.CMD;
    EXECUTE S1 INTO V_DUMMY;
    IF V_DUMMY IS NOT NULL THEN
      CALL DBMS_OUTPUT.PUT_LINE ('Found in: "' || C1.TABSCHEMA || '"."' || C1.TABNAME || '"');
    END IF;
  END FOR;

END@

SET SERVEROUTPUT OFF@

相关问题