2012-10-03 223 views
0

我有一個存儲過程,它返回一堆工會的行。我想要做的是看看select語句是否不產生任何行,如果是,執行另一個腳本。Sql select count with count

這是我在存儲過程中使用的當前sql選擇。請讓我知道我能做到這一點。

SELECT name AS [Name], address1 AS Address1, address2 AS Address2, city AS City, 1 AS DeliveryTypeKey, email AS Email, 
    (SELECT TOP 1 c_phone_number 
    FROM phone WITH (NOLOCK) 
    WHERE value = @value) AS Fax 
    FROM #Cities x  
INNER JOIN prov p WITH (NOLOCK) ON x.ckey = p.pkey 
UNION 
SELECT name AS [Name], address1 AS Address1, address2 AS Address2, city AS City, 1 AS DeliveryTypeKey, email AS Email, 
    (SELECT TOP 1 c_phone_number 
    FROM phone WITH (NOLOCK) 
    WHERE value = @value) AS Fax 
    FROM #Cities1 x  
    INNER JOIN prov1 p WITH (NOLOCK) ON x.ckey = p.pkey 
UNION 
SELECT name AS [Name], address1 AS Address1, address2 AS Address2, city AS City, 1 AS DeliveryTypeKey, email AS Email, 
    (SELECT TOP 1 c_phone_number 
    FROM phone WITH (NOLOCK) 
    WHERE value = @value) AS Fax 
FROM #Cities2 x  
INNER JOIN prov2 p WITH (NOLOCK) ON x.ckey = p.pkey 
+0

爲什麼你不能只是把它包裝在一個子查詢返回的計數? –

+0

由於我在查詢中有大約20個聯合,子查詢得到實際的計數,並且實際查詢它變成了一個巨大的存儲過程。我試圖看到比這更好的選擇,如果不是,我會去用子查詢方法。 – user1663996

+0

#Cities,#Cities1等表格之間有什麼區別?他們可以合併,以消除聯盟? –

回答

1

使用ROWCOUNT函數來檢查是否有任何行,其中返回:

DECLARE @table TABLE 
    ( 
    DATA INT 
) 

INSERT @table 
VALUES (0) 

SELECT * 
FROM @table 
WHERE DATA > 0 

IF @@ROWCOUNT = 0 
    SELECT 'run' 
ELSE 
    SELECT 'Don''t run'