数据库中有A、B、C三个表,我在存储过程中对A表进行查询,如果有记录就不执行下面的代码,如果没有记录(if @@ROWCOUNT =0)就查询B表,如果有记录就不执行下面的代码,如果也没有数据就查询C表,我的希望是返回一个记录集,现在情况是如果A、B表都没有数据,而c表有数据,那么返回的除了C表记录外还有A、B表的空记录!这个是我在查询分析器中测试出来的,请问如何解决?我只要1个记录集

解决方案 »

  1.   

    Try:Select * from A 
    Union All
    Select * from B Where Not Exists (Select * from A)
    Union All
    Select * from C Where Not Exists (Select * from A) And Not Exists (Select * from B)
      

  2.   


    --建立測試環境
    Create Table A
    (ID Int,
     Name Varchar(10))Create Table B
    (ID Int,
     Name Varchar(10))Create Table C
    (ID Int,
     Name Varchar(10))
    --測試
    --三個表都有數據的情況下
    Insert A Select 1,'A'
    Insert B Select 2,'B'
    Insert C Select 3,'C'Select * from A 
    Union All
    Select * from B Where Not Exists (Select * from A)
    Union All
    Select * from C Where Not Exists (Select * from A) And Not Exists (Select * from B)
    --B、C表有數據,A表沒有數據的情況
    Delete from ASelect * from A 
    Union All
    Select * from B Where Not Exists (Select * from A)
    Union All
    Select * from C Where Not Exists (Select * from A) And Not Exists (Select * from B)
    --C表有數據,A、B表沒有數據的情況
    Delete from BSelect * from A 
    Union All
    Select * from B Where Not Exists (Select * from A)
    Union All
    Select * from C Where Not Exists (Select * from A) And Not Exists (Select * from B)
    --刪除測試環境
    Drop Table A,B,C
    --結果
    /*
    --第一種情況
    ID Name
    1 A--第二種情況
    ID Name
    2 B--第三種情況
    ID Name
    3 C
    */
      

  3.   

    create proc aaa
    as 
    if (select num=count(1) from A表)>0
    begin
     select * from A表
    end
    else
    begin
      if (select num=count(1) from B表)>0
         select * from B表
       else
        select * from C表
    end