有没有办法让if语句确定是否需要连接?
我需要这个,因为我查询的数据中有多个外键。如果任何外键为null,我需要更改SQL语句。我想写一个可以知道任何空值的语句。
这就是我想要做的......
select a.*,b.* from table1 a inner join table2 b on a.id = b.id
if a.InspectorID is not null
{inner join table3 c on a.InspectionID = c.id}
else do nothing...
答案 0 :(得分:1)
我不确定,如果你可以有条件地连接表,但t-sql中的“if”语句是calles case
答案 1 :(得分:1)
使用union
select a.*,b.*
from table1 a
inner join table2 b on a.id = b.id
inner join table3 c on a.InspectionID = c.id
union all
select a.*,b.*
from table1 a
inner join table2 b on a.id = b.id
where a.InspectionID is null
答案 2 :(得分:1)
试试这个......
select a.*,b.* from table1 a inner join table2 b on a.id = b.id
left join table3 c on a.InspectionID = c.id
where a.InspectorID is null or a.InspectionID = c.id
答案 3 :(得分:1)
如果我理解正确,您可以使用:
select a.*,b.*,c.fields
from table1 a inner join table2 b on a.id = b.id
left join table3 c on a.InspectionID = c.id
where a.InspectionID IS NOT NULL
答案 4 :(得分:-1)
使用动态sql。有关动态sql的详细信息,请访问: http://exacthelp.blogspot.in/2013/02/writing-dynamic-sql-queries-in-sql.html