如果在sql查询中声明

时间:2012-02-03 19:20:34

标签: sql

无论如何,我基本上可以在sql子句中执行以下操作,(我知道语法不正确,但这不是重点,这是主意)

set rs = select title, copy, masterID from table1

//if the masterID is not 0 then instead of using the copy from table1, use the copy from table2

if masterID<>0 then set rs2 = "select copy from table2 where masterID =" & masterID copy = rs(0)

我希望这是有道理的。期待听到您的回复。谢谢!

2 个答案:

答案 0 :(得分:3)

我认为你想要的是:

select title, 
       case when t1.masterID <> 0 then t2.case else t1.case end as copy, 
       masterID
from table1 as t1
left join table2 as t2
    on t1.masterID = t2.masterID

答案 1 :(得分:0)

DECLARE @masterID int
if(@masterID <> 0)
    select copy from table2 where masterId = @masterID
 else
    select title, copy, masterID from table1