我需要从多个不同的视图检索记录。视图具有完全相同的列。我想使用*参数,因为会不断添加新视图,并且使用UNION ALL
时,总是会有相同的代码。
有效方法:
SELECT ID, TEXT FROM TABLE1
UNION ALL
SELECT ID, TEXT FROM TABLE2
UNION ALL
SELECT ID, TEXT FROM TABLE3
UNION ALL
SELECT ID, TEXT FROM TABLE4
UNION ALL
SELECT ID, TEXT FROM TABLE5
UNION ALL
SELECT ID, TEXT FROM TABLE6
UNION ALL
SELECT ID, TEXT FROM TABLE7
我想要什么:
SELECT * FROM TABLE1
UNION ALL
SELECT * FROM TABLE2
UNION ALL
SELECT * FROM TABLE3
UNION ALL
SELECT * FROM TABLE4
UNION ALL
SELECT * FROM TABLE5
UNION ALL
SELECT * FROM TABLE6
UNION ALL
SELECT * FROM TABLE7´
如果我这样做,会出现以下错误:
ORA-01790: expression must have same datatype as corresponding expression
更新:
对不起,我的错。 视图并不完全相同,因为一种数据类型已转换为数字,另一种数据类型已转换为varchar。 问题解决了。
答案 0 :(得分:0)
如果两个表都具有完全相同的数字列和数据类型,则它应该工作 参见下面的示例
with cte1 (st,dt) as
(
select 'New' as st, '30/09/2014 3:48:10 PM' as dt from dual
union all
select 'Open' as st, '30/09/2014 3:48:10 PM' as dt from dual
union all
select 'Open' as st, '20/09/2014 3:48:10 PM' as dt from dual
union all
select 'Qued' as st, '18/06/2015 1:31:30' as dt from dual
)
,
t2(st,dt) as
(
select 'New' as st, '30/09/2014 3:48:10 PM' as dt from dual
union all
select 'Open' as st, '30/09/2014 3:48:10 PM' as dt from dual
union all
select 'Open' as st, '20/09/2014 3:48:10 PM' as dt from dual
union all
select 'Qued' as st, '18/06/2015 1:31:30' as dt from dual
)
select * from cte1
union all
select * from t2
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=430f00a6616515f2cdaefe61990285d0
答案 1 :(得分:0)
视图并不完全相同,因为一种数据类型被转换为数字,另一种数据类型被转换为varchar。
Oracle 11g R2架构设置:
CREATE TABLE TABLE1 (
id NUMBER(8,0),
text VARCHAR2(400),
value NUMBER
);
CREATE TABLE TABLE2 (
id NUMBER(8,0),
text VARCHAR2(200),
value VARCHAR2(20)
);
INSERT INTO TABLE1 VALUES ( 1, '1', 1 );
INSERT INTO TABLE1 VALUES ( 2, '2', '2' );
查询1 :如果数据类型不匹配,则会出现异常:
SELECT * FROM TABLE1
UNION ALL
SELECT * FROM TABLE2
Results :
ORA-01790: expression must have same datatype as corresponding expression
查询2 :
要解决此问题,您可以在具有匹配数据类型的表上使用SELECT * FROM ...
并显式命名列,并在具有不同数据类型的表上应用转换:
SELECT * FROM TABLE1
UNION ALL
SELECT id, text, TO_NUMBER( value ) FROM TABLE2
Results :
| ID | TEXT | VALUE |
|----|------|-------|
| 1 | 1 | 1 |
| 2 | 2 | 2 |