我在sql中有10个表,并从id与UNION ALL匹配的表中获取记录;但我的问题是结果发现查询停止进一步处理;就像c#
中函数的return语句一样答案 0 :(得分:1)
select ... from T1 where ...
if @@RowCount = 0
select ... from T2 where ...
if @@RowCount = 0
select ... from T3 where ...
如果您需要对结果进行其他处理,可以SELECT INTO
临时表或INSERT
/ SELECT
表变量。
编辑:根据OP的评论,我可以建议:
declare @Table1 as Table ( Id Int )
declare @Table2 as Table ( Id Int )
declare @Table3 as Table ( Id Int )
declare @Result as Table ( Id Int, Source VarChar(10) )
-- Try changing the following line to use different tables and values.
insert into @Table2 ( Id ) values ( 42 )
insert into @Result
select Id, 'Table1' from @Table1 where Id = 42
if @@RowCount = 0
insert into @Result
select Id, 'Table2' from @Table2 where Id = 42
if @@RowCount = 0
insert into @Result
select Id, 'Table3' from @Table3 where Id = 42
select * from @Result
答案 1 :(得分:0)
如果您打算继续使用UNION ALL,则无法使用。
为什么不一次选择并在每次选择后检查您是否有所需信息?如果是,请结束,如果没有,请继续并进行另一次选择。
答案 2 :(得分:0)
IF (exists(select 1 from table1 where condition))
select col1, col2 from table1
where condition
else if(exists(select 1 from table2 where condition))
select col1, col2 from table2
where condition
else if(exists(select 1 from table3 where condition))
select col1, col2 from table3
where condition
... continue until table10