两个SQL语句,如果没有结果,忽略第一个返回?

时间:2022-09-02 00:25:47

I have a sql statement SELECT * FROM table1 WHERE ....; SELECT * FROM table2 WHERE ....

我有一个sql语句SELECT * FROM table1 WHERE ....; SELECT * FROM table2 WHERE ....

What I want is to get the results from the first select statement if it returns results, but if it doesn't, I want to ignore it and just get the results from the second select statement. Is there a way I can do this just using SQL?

我想要的是从第一个select语句中获取结果,如果它返回结果,但如果没有,我想忽略它,只是从第二个select语句得到结果。有没有办法只使用SQL才能做到这一点?

I'm getting this returned to me as a datatable, using a dataadapter to fill the datatable from the above SQL statement. I can't change that part, or switch to filling a dataset (for reasons I won't get into, but it just can't be changed).

我将它作为数据表返回给我,使用dataadapter从上面的SQL语句填充数据表。我无法更改该部分,或切换到填充数据集(原因我不会进入,但它无法更改)。

2 个解决方案

#1


3  

Assuming both queries return the same number and type of columns, one way to do this would be:

假设两个查询都返回相同数量和类型的列,一种方法是:

select * from table1 where ... /* query 1 conditions */
union all
select * from table2 where ... /* query 2 conditions */
and not exists
(select 1 from table1 where ... /* query 1 conditions */)

#2


0  

A couple options. You can check the count first:

几个选项。您可以先查看计数:

If (select count(*) from table1 where...) > 0
begin
    select * from table1 where...
end
else
begin
    select * from table2 where...
end;

if both result sets are identical in structure, you can save the count check (and thus improve performance) by using a temp table:

如果两个结果集的结构相同,则可以使用临时表保存计数检查(从而提高性能):

create table #temp (col1 int, col2 varchar(10), ...);

insert #temp
select * from table1 where...;

if @@rowcount = 0 
begin
    insert #temp
    select * from table2 where...
end;

select * from #temp;

#1


3  

Assuming both queries return the same number and type of columns, one way to do this would be:

假设两个查询都返回相同数量和类型的列,一种方法是:

select * from table1 where ... /* query 1 conditions */
union all
select * from table2 where ... /* query 2 conditions */
and not exists
(select 1 from table1 where ... /* query 1 conditions */)

#2


0  

A couple options. You can check the count first:

几个选项。您可以先查看计数:

If (select count(*) from table1 where...) > 0
begin
    select * from table1 where...
end
else
begin
    select * from table2 where...
end;

if both result sets are identical in structure, you can save the count check (and thus improve performance) by using a temp table:

如果两个结果集的结构相同,则可以使用临时表保存计数检查(从而提高性能):

create table #temp (col1 int, col2 varchar(10), ...);

insert #temp
select * from table1 where...;

if @@rowcount = 0 
begin
    insert #temp
    select * from table2 where...
end;

select * from #temp;