【问题标题】:How to Execute an SQL Anonymous Block in DB2?如何在 DB2 中执行 SQL 匿名块?
【发布时间】:2017-02-16 21:04:11
【问题描述】:

我想通过数据包含“ABC”的列架构进行搜索。在 Oracle PL/SQL 中,我会这样做:

DECLARE
  v_cnt integer;
BEGIN

  for i in (select tabname, colname
              from all_tab_cols --syscat.columns
             where tabschema = 'DATA'
          order by tabname, colname)
  loop 

    execute immediate '
    select count(1)
    from '||i.tabname||'
    where upper('||i.colname||') like ''%ABC%''' into v_cnt;

    if v_cnt > 0 then 
      dbms_output.put_line(i.tabname||' - '||i.colname)
    end if;

  end loop;

END;

但是它位于 DB2 数据库中。我已尝试在线搜索正确的语法,但找不到。 syscat.columns 是 all_tab_cols 的 oracle 等价物,因此我只需要 DB2 中匿名 SQL 块的正确语法。

有人能帮我看看语法吗?

【问题讨论】:

  • 什么 DB2 版本和平台?
  • 版本为 DB2 v10.5.0.5
  • @Fermin -- DB2 可以在许多不同的平台上运行 -- 您也需要包含这些信息。

标签: sql oracle plsql db2 db2-luw


【解决方案1】:

首先,DB2 for LUW 提供 Oracle 兼容模式——如果为您的数据库实例启用它,您可以简单地使用 Oracle PL/SQL 语法,它会工作,包括对 @ 的引用987654322@。

如果未启用 Oracle 兼容性,则 DB2 SQL PL 语法会有些不同。具体来说,DECLARE 进入 inside BEGIN ... END 块,您需要 CALL 存储过程 DBMS_OUTPUT.PUT_LINE()。其他一切应该都可以正常工作。

有关compound SQL syntax的更多信息。

【讨论】:

    【解决方案2】:

    试试这样的,谁知道呢:

    BEGIN ATOMIC
    DECLARE v_cnt integer;
    DECLARE text VARCHAR(128);
    DECLARE stmt STATEMENT;
    
      for i as (select tabname, colname
                  from all_tab_cols --syscat.columns
                 where tabschema = 'DATA'
              order by tabname, colname)
      do 
    
    
    --According to Graeme Birchall this shouldn't work  
    --        execute immediate '
    --        select count(1)
    --        from '||i.tabname||'
    --        where upper('||i.colname||') like ''%ABC%''' into v_cnt;
    -- db2 maybe more verbose:
    
       set text = 'select count(1) from '||i.tabname||' where upper('||i.colname||') like ''%ABC%''';
    
    PREPARE stmt FROM text;
    EXECUTE stmt INTO v_cnt;
    
            if v_cnt > 0 then 
              dbms_output.put_line(i.tabname||' - '||i.colname)
            end if;
    
          end for;
    
        END;
    

    【讨论】:

      猜你喜欢
      • 2017-09-02
      • 2015-03-02
      • 1970-01-01
      • 2014-09-30
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      相关资源
      最近更新 更多