如果表中不存在该列,我试图为列选择默认值。以下代码似乎没有给出我预期的输出。
SELECT CustomerID, (select case when exists (select *
from INFORMATION_SCHEMA.COLUMNS
where table_name = 'Customers' and
column_name = 'Age'
)
then Age
else 0 as Age
end)
FROM (select * from Customers);
由于Age列不存在于表中,因此结果应为: -
CustomerID | Age
-----------|----
Cust01 | 0
Cust02 | 0
有人可以在上面的代码段中向我建议解决方案或错误。
答案 0 :(得分:0)
正如专家评论中所提到的,您需要使用Oracle PLSQL块并使用动态sql实现您的需求。请参阅下面相同的代码,其中记录了您的要求。您可以尝试使用以下代码实现代码:
declare
var number;
var2 varchar2(4000);
type abc is record
( col1 number,
col2 number);
type var3 is table of abc index by pls_integer;
var4 var3;
begin
select count(1)
into var
from employee;
var2:= 'select A, '||case when var is null then 1 else 2 end || ' from test where rownum < 10';
dbms_output.put_line(var2);
execute immediate var2 bulk collect into var4;
for rec in 1..var4.last
loop
dbms_output.put_line(var4(rec).col1 ||',' ||var4(rec).col2);
end loop;
end;
输出:
select A, 2 from test where rownum < 10
1444,2
1445,2
1446,2
1447,2
1448,2
1449,2
1450,2
1451,2
1452,2