SQL-是否可以在插入值中包含if

Kas*_*ade 1 sql oracle

我需要编写一个脚本来将从一个表中选择的数据插入另一个表中。旧表在一个列中存储值“是”,但我想插入1而不是“是”

有什么办法可以做到这一点。在我的脑海中,这就是我要做的:

insert into new_table (new_col1, new_col2)
values (select from old_table(old_col1, (if old_col2='Yes' then 1 else 0))
Run Code Online (Sandbox Code Playgroud)

a_h*_*ame 5

第一:如果您的插入基于SELECT,则不得使用该VALUES子句。

要获取条件值,请使用(ANSI标准)CASE语句:

insert into new_table (new_col1, new_col2)
select old_col1, 
       case 
         when old_col2 = 'Yes' then 1 
         else 0 
       end
from old_table
Run Code Online (Sandbox Code Playgroud)

一个Oracle唯一更紧凑的形式是decode()语句(但我建议使用CASE,因为它对于其他DBMS也更具可读性和可移植性)

insert into new_table (new_col1, new_col2)
select old_col1, 
       decode(old_col2, 'Yes', 1, 0)
from old_table
Run Code Online (Sandbox Code Playgroud)