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)
--建立測試環境 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 */
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
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)
--建立測試環境
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
*/
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