我需要編寫腳本以將從一個表中選擇的數據插入另一個表中。舊錶在一列中存儲值「是」,但我想插入1而不是「是」SQL - 是否有可能在插入值的內部有if if
有沒有辦法做到這一點。在我的腦海中,這是我想要做的:
insert into new_table (new_col1, new_col2)
values (select from old_table(old_col1, (if old_col2='Yes' then 1 else 0))
我需要編寫腳本以將從一個表中選擇的數據插入另一個表中。舊錶在一列中存儲值「是」,但我想插入1而不是「是」SQL - 是否有可能在插入值的內部有if if
有沒有辦法做到這一點。在我的腦海中,這是我想要做的:
insert into new_table (new_col1, new_col2)
values (select from old_table(old_col1, (if old_col2='Yes' then 1 else 0))
首先:如果你立足於a。選擇插入,則不能使用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
的甲骨文只有更緊湊的形式將是解碼()語句(但我建議你使用的情況下,因爲它是更具可讀性和移植到其他DBMS也一樣)
insert into new_table (new_col1, new_col2)
select old_col1,
decode(old_col2, 'Yes', 1, 0)
from old_table
你在找什麼是CASE
聲明。
CASE
WHEN old_col2='Yes' then 1
ELSE 0
END
見http://stackoverflow.com/q/8176902/447514 – Gaius