例如对于 Oracle:我想要一些临时表用于合并:

MERGE INTO my_target_table
USING (
        WITH tbl1 AS (       SELECT 'a'   col1 FROM dual            -- <--- THIS
                       UNION SELECT 'foo' col1 FROM dual            -- <--- IS
                       UNION SELECT 'doh' col1 FROM dual            -- <--- CRAPPY
                     ),
             tbl2 AS (       SELECT 'b'   col2, 'c' col3 FROM dual  -- <--- THIS
                       UNION SELECT 'x'   col2, 's' col3 FROM dual  -- <--- ALSO
                     )
        SELECT col1, col2, col3 FROM tbl1 CROSS JOIN tbl2
      ) my_source_view
   ON (     my_target_table.col1 = my_source_view.col1
        AND my_target_table.col2 = my_source_view.col2
      )
 WHEN MATCHED THEN UPDATE
                      SET my_target_table.col3 = my_source_view.col3
 WHEN NOT MATCHED THEN INSERT(               col1,                col2,                col3)
                       VALUES(my_source_view.col1, my_source_view.col2, my_source_view.col3)
;

这里的 SELECT UNION SELECT 模式真的很烦人,我觉得它很可怕(重复、冗长)。

您是否有伪造类似查询的技巧,无论是否特定于 Oracle?

谢谢

最佳答案

伯努瓦,

您可以将其用于具有一列的表:

SQL> with tbl1 as
  2  ( select column_value col1
  3      from table(sys.dbms_debug_vc2coll('a','foo','doh'))
  4  )
  5  select *
  6    from tbl1
  7  /

COL1
------------------------------------------------------------
a
foo
doh

3 rows selected.

对于不止一列,您需要创建两种类型(或使用现有类型),如下所示:
SQL> create type ot is object
  2  ( col1 varchar2(1)
  3  , col2 varchar2(1)
  4  );
  5  /

Type created.

SQL> create type ntt is table of ot;
  2  /

Type created.

SQL> with tbl2 as
  2  ( select *
  3      from table(ntt(ot('b','c'),ot('x','s')))
  4  )
  5  select *
  6    from tbl2
  7  /

C C
- -
b c
x s

2 rows selected.

问候,
抢。

关于sql - 有没有一种有效的方法来避免 SQL 中固定值的联合?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5420126/

10-13 04:26