2016-08-18 125 views
-1

我有以下查詢(SQL SERVERSQL - 如何UNION ALL IF @RowCount

SELECT name, number, position, workingyears 
FROM employee 
WHERE type = 'A' 

IF @@ROWCOUNT = 0 
     BEGIN 

SELECT name, number, position, workingyears 
FROM employee 
WHERE type = 'B' 

     END 

如果首先選擇的結果是空的話,我需要做其他的選擇都將有相同的列但不同的過濾器。我怎樣才能得到一個表。

+0

'的這個當@@ ROWCOUNT = 0的兩個表的結果。我怎麼能聯盟?'可以請你詳細說明 – TheGameiswar

回答

2

您可以檢查是否存在type = 'A',然後使用1st或2nd查詢。

if exists(select 1 from employee WHERE type = 'A') 

SELECT name, number, position, workingyears 
FROM employee 
WHERE type = 'A' 

else 

SELECT name, number, position, workingyears 
FROM employee 
WHERE type = 'B' 

或者在一個查詢中。

SELECT name, number, position, workingyears 
FROM employee 
WHERE type = case when exists(select 1 from employee WHERE type = 'A') then 'A' 
      else 'B' end 
2

你可以試試這個:

SELECT name, number, position, workingyears 
FROM employee 
WHERE type = 'A' 

UNION ALL 

SELECT name, number, position, workingyears 
FROM employee 
WHERE (type = 'B' and NOT EXISTS(SELECT 1 FROM employee WHERE type = 'A'))