我的查询如下:
select *
from BASE_TABLE
inner join (
select * from TABLE_A
) t on BASE_TABLE.ID = t.ID
并希望使嵌套查询成为条件,例如:
select *
from BASE_TABLE
inner join (
if @var = 1
select * from TABLE_A
else
select * from TABLE_B
) t on BASE_TABLE.ID = t.ID
有可能吗? 查询在存储过程中使用。解决方案应该适用于SQL Server和Oracle,或者至少适用于SQL Server。
答案 0 :(得分:2)
这个怎么样:
SELECT
*
FROM
BASE_TABLE
INNER JOIN (
SELECT col1, col2, colN FROM TABLE_A WHERE @var IN (1) -- "if"
UNION
SELECT col1, col2, colN FROM TABLE_B WHERE @var IN (2) -- "else if"
UNION
SELECT col1, col2, colN FROM TABLE_C WHERE @var NOT IN (1, 2) -- "else"
) t ON t.ID = BASE_TABLE.ID
答案 1 :(得分:0)
我会这样做(但是你需要指定字段;你不能使用select *
语法):
select base.ID, base.Field1, base.Etc, Field1 = case when @var=1 then a.Field1 else b.Field1 end,
Field2 = case when @var=1 then a.Field2 else b.Field2 end
from BASE_TABLE base
left join TABLE_A a on base.ID = a.ID
left join TABLE_B b on base.ID = b.ID
答案 2 :(得分:0)
请尝试以下查询
declare @var int=1
declare @qry nvarchar(max)
set @qry='select * from BASE_TABLE ('
if @var=1
set @qry=@qry+ 'select * from TABLE_A'
else
set @qry=@qry+ 'select * from TABLE_B'
set @qry=@qry+')t on BASE_TABLE.ID = t.ID'
exec (@qry)