`
luzl
  • 浏览: 574276 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

db2 SQL: value(), values(), with, recursive SQL

    博客分类:
  • DB2
阅读更多
comment:
-- comment should be on a separate line outside an SQL statement

select 1 from (values 1) as aa -- this is not a valid db2 comment


way to create simple tests against dynamic table:
select 'a' as col1,'b' as col2 from table (values 1) as dummy

or shorter:
select 'a','b' from (values 1) qq

In fact, for simple tests you don't even need select and a dummy table.
values ( 'mama', 1)
values (cast (2.5 as decimal(10,3)) * cast (2.5 as decimal(10,3)) )

using cast( ) and values( ), building null values on the fly:
select
  'abc' as col1,
  cast(null as varchar(80)) as col2
from
  table (values (1,2),(3,4)) as dummy

Hint how to make running tests from the prompt easy:
I create 2 aliases:

alias vv='vi test.sql'
alias rr='db2 -tvf test.sql'

Type 'vv' to edit test.sql file (remember - you should end each SQL statement with a semicolon ';')
Then type 'rr' to run this SQL.

simple insert:
insert into inst1.test (A) values ('a'), ('b'), ('c')

using case:
select
  case
    when 1<2 then 'mama'
    when 1>2 then 'papa'
  end
  as person
from table (values 1) as qq

concatenating:
select 'mama' concat ' papa' from table (values 1) as qq;
select 'mama' || ' papa' from table (values 1) as qq;

union, intersect & except:
select .. from T1 union T2 - remove duplicates
select .. from T1 union all T2  -- preserve duplicates
select .. from T1 intersect T2 - remove duplicates
select .. from T1 intersect all T2  -- contains min number of repetition
select .. from T1 except T2 - remove duplicates, then do except
select .. from T1 except all T2 do except, then remove duplicates

value( ) function:
-- value() function - accepts a variable number of parameteres and returns a
first non-null value
-- parameters should be of compatible types
-- the actual name for this function is coalesce() - means "to arise from a
combination of distinct elements"
select value(1,2) from (values 1) as aa
-- returns 1
select value(cast(null as int),2) from (values 1) as aa
-- returns 2
select value(cast(null as int),cast(null as int),3) from (values 1) as aa
-- returns 3

------------------------------------------------------------

2 ways (common table and inline table expression) to define table dynamically in the SQL statement:

with tree (id,pid) as (
    values (1,2), (2,3), (3,4), (4, cast(null as int)), (5,3), (6,5)
  )
select * from tree

        ID      PID
        1       2
        2      3
        3       4
        4       [NULL]
        5       3
        6       5
-------------------------------------------- another way to do the same
select * from (
  values (1,2), (2,3), (3,4), (4, cast(null as int)), (5,3), (6,5)
  )
  as a

Getting root of the tree using recursive SQL:

with

  tree (id,pid) as (
    values (1,2), (2,3), (3,4), (4, cast(null as int)), (5,3), (6,5)
  ),

  rr (id,pid) as (
    select tr.id, tr.pid from tree tr where tr.id=1
      union all
    select tt.id,tt.pid from tree tt, rr
    where tt.id = rr.pid
  )

select id from rr where rr.pid is null

More recursive SQL:

We have table storing a tree (each row has id and parent_id).
To get root id for a given id (12345) we fill out temporary table rr:
first with given id and its parent_id. Then union with recursively calculated
id and parent_id as we go up the tree:

  with rr (parent_id, id) as
  (
      select p.parent_id, p.id
        from mytree p
       where p.id = 12345
  union all
      select p.parent_id, p.id
        from mytree p, rr
       where p.id = rr.parent_id
  )
  select id ROOT from rr where parent_id is null;

Here is an example going in the oposite direction (down the tree). We showing the whole tree under a given id:

  with rr (id, level) as
  (
      select id, 1
        from mytree
       where id = 10001
  union all
      select child.id, parent.level + 1
        from mytree child, rr parent
       where parent.id = child.parent_id
  )
  select * from rr;

  Result:
           ID         LEVEL
  ----------------------------
         10001            1
         29361            2
         23044            3
         25162            3
         25302            3

Here is how to combine 2 above queries together:

----------------------------------------------------------------------------
  -- Given any node in any tree, this query will drill up to the top
  -- level of the tree, and then query down to give all nodes that exist
  -- within the tree (i.e. given any node_id, show the whole
  -- tree that contains it).
  --
  -- Note: This query will never go deeper than 'stop_level' levels (10).
  ----------------------------------------------------------------------------

  with rec_root (parent_id, child_id, sub_query, level, stop_level) as
  (
      select my_parent_id, my_id, 1, 0, 0
        from mydb.mytable
       where my_id = 25162
  union all
      select parent.my_parent_id, parent.my_id, 2, 1, child.level + 1
        from mydb.mytable parent, rec_root child
       where parent.my_id = child.parent_id
         and sub_query in (1,2)
         and child.stop_level < 10
  union all
       select my_parent_id, my_id, 3, parent3.level + 1, parent3.level + 1
         from rec_root parent3, mydb.mytable child3
        where parent3.child_id = child3.my_parent_id
          and (   (parent3.sub_query = 2 and parent3.parent_id is null)
                or parent3.sub_query = 3
              )
          and parent3.stop_level < 10
  )
  select * from rec_root
   where parent_id is null
      or sub_query = 3;
分享到:
评论
3 楼 anttu 2012-05-15  
2 楼 anttu 2012-05-11  
                         
1 楼 anttu 2012-05-11  

相关推荐

    CF12 DB2 SQL Workshop

    《CF12 DB2 SQL Workshop》是一份IBM官方提供的详细教程,主要针对DB2数据库管理系统中的SQL语言进行深入讲解。本教程分为七个单元,旨在帮助用户掌握SQL在DB2环境中的核心应用,提升数据管理和分析能力。以下是各...

    数据库设计之递归树查询

    在支持`WITH RECURSIVE`的数据库(如PostgreSQL、SQL Server)中,递归查询的通用语法如下: ```sql WITH RECURSIVE cte_name AS ( -- 初始化子查询(非递归部分) SELECT column1, column2, ... FROM table_...

    oracle转DB2 对照

    CREATE TRIGGER connect_audit_trg NO CASCADE BEFORE INSERT ON connect_audit REFERRING NEW AS n FOR EACH ROW MODE DB2SQL BEGIN ATOMIC SET n.timestamp = CURRENT_TIMESTAMP; END ``` - 注意点: 在DB2中,...

    recursive sql.txt

    postgre sql recursive sql. 在postgoresql 中使用recursive的脚本实现循环查询结果

    Inverse dynamics with recursive Newton-Euler:Inverse dynamics with recursive Newton-Euler of a open kinematic chain and standard DH-parameters-matlab开发

    使用标准 DH 参数描述的开放运动链的递归 Newton-Euler 逆动力学可选的: 机器人工具箱用于比较: http : //www.petercorke.com/RTB/ 下载并解压缩文件。 使用“pathtool”命令将路径添加到 MATLAB。...

    ORACLE转DB2对照全解

    WITH RECURSIVE hierarchy(id, parent_id) AS ( SELECT id, parent_id FROM table WHERE id = root_id UNION ALL SELECT t.id, t.parent_id FROM table t JOIN hierarchy h ON t.parent_id = h.id ) SELECT * ...

    sql里面 with...as 是什么意思?如何使用?

    ### SQL中的WITH...AS语句详解 在SQL中,`WITH...AS`是一种非常有用的特性,主要用于定义公用表表达式(Common Table Expression,简称CTE)。通过CTE,我们可以更清晰地组织复杂的查询语句,并且能够提高某些类型...

    ORACLE和SQL Server的语法区别

    - **SQL Server:** SQL Server提供了类似的SELECT语句结构,但并不支持`START WITH ... CONNECT BY` 子句。为了实现层次结构查询,可以使用递归公共表表达式(Recursive CTEs)。 ```sql SELECT select_list ...

    SQL With 递归

    在SQL中,`WITH`语句,也称为公共表表达式(Common Table Expression,简称CTE),是一种非常有用的工具,特别是在处理递归查询时。它允许我们定义一个临时的结果集,这个结果集可以在同一个查询中被多次引用,提高...

    SQL袖珍参考手册(第3版)

    - **中文名**: SQL袖珍参考手册(第3版,涵盖DB2,MySQL,Oracle,PostgreSQL,SQL Server) - **原名**: SQL Pocket Guide: A Guide to SQL Usage - **作者**: Jonathan Gennick - **资源格式**: PDF - **版本**: ...

    yolov1、yolov2、yolov3、yolov4、yolov5、yolov6、yolov7等论文 .zip

    6)DetectoRS: Detecting Objects with Recursive Feature; 7)YOLOv6: A Single-Stage Object Detection Framework for Industrial Applications; 8)YOLOv7: Trainable bag-of-freebies sets new state-of-the-art ...

    yolov1、yolov2、yolov3、yolov4、yolov5、yolov6、yolov7等论文 1.zip

    6)DetectoRS: Detecting Objects with Recursive Feature; 7)YOLOv6: A Single-Stage Object Detection Framework for Industrial Applications; 8)YOLOv7: Trainable bag-of-freebies sets new state-of-the-art ...

    yolov1、yolov2、yolov3、yolov4、yolov5、yolov6、yolov7等论文

    6)DetectoRS: Detecting Objects with Recursive Feature; 7)YOLOv6: A Single-Stage Object Detection Framework for Industrial Applications; 8)YOLOv7: Trainable bag-of-freebies sets new state-of-the-art ...

    SQL Server CTE 递归查询全解1

    SQL Server中的递归查询主要通过CTE(公共表表达式)来实现,它是一种非常强大的工具,特别适用于处理层次结构数据。CTE是T-SQL脚本中的临时结果集,可以用于复杂的查询,尤其是需要递归操作的情况。本文将深入探讨...

    SQL 语句大全 SQL 语句大全

    - **递归查询**:使用WITH和RECURSIVE关键字处理层次结构数据。 - **并行查询**:在多处理器系统上加速查询执行。 学习并熟练掌握这些SQL语句将使你能够高效地操作和管理数据库,无论是在开发、数据分析还是...

    记录一次隐含参数也不好解决的备份恢复.pdf

    12 ORA‐00604: error occurred at recursive SQL level 2 13 ORA‐01555: snapshot too old: rollback segment number 7 with name 14 "_SYSSMU7_4222772309$" too small 15 Process ID: 1730 16 Session ID: 1996 ...

    Iso-Recursive-Subtyping:重温 Iso-Recursive 子类型化

    重温 Iso-Recursive 子类型化(工件)抽象的这个包包含与论文“Revisiting Iso-Recursive Subtyping”相关的 Coq 公式。 本文档解释了如何运行 Coq 公式。入门我们强烈建议您通过opam2安装 Coq 证明助手。 安装 (&gt;=...

    Inside Microsoft SQL Server 2008 T-SQL Querying

    Delve into the internal architecture of T-SQL—and unveil the power of set-based querying—with comprehensive reference and advice from a highly regarded T-SQL expert and members of Microsoft's SQL ...

    PostgreSQL_与_MS_SQLServer比较

    - **MS SQL Server** 使用 `WITH RECURSIVE` 进行递归查询。 - **PostgreSQL** 同样支持使用 `WITH RECURSIVE`。 #### 系统对象名(表名、索引等)大小写敏感性 - **PostgreSQL** 默认对标识符(如表名、列名等)是...

Global site tag (gtag.js) - Google Analytics