1

我在 sql 中有 10 个表,并从 id 与 UNION ALL 匹配的表中获取记录;但我的问题是结果发现查询停止进一步处理;就像c#函数中的return语句一样

4

3 回答 3

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
于 2012-05-31T12:54:48.027 回答
0

如果您打算继续使用 UNION ALL 是不可能的。

您为什么不一次选择并在每次选择后检查您是否有所需的信息?如果是,则结束它,如果不是,则继续并进行另一次选择。

于 2012-05-31T12:06:48.960 回答
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
于 2012-05-31T12:18:15.943 回答