2013-12-20 190 views
0

我有存儲過程,裏面我有選擇語句,插入和更新,但在我的select語句中,我想將結果存儲在變量中,以便稍後可以訪問它在我的更新聲明中。如何將結果首先存儲在變量中?這是我的選擇語句:如何將sql結果存儲到sql server 2008中的變量

SELECT 
    REV1 = COUNT(CASE WHEN QTR = 1 AND MAIN_SAT =1 AND ACTIVE_FLAG = 1 THEN 1 END), 
    REV2= COUNT(CASE WHEN QTR = 1 AND MAIN_EKL =1 AND ACTIVE_FLAG = 1 THEN 1 END), 
    REV3= COUNT(CASE WHEN QTR = 1 AND MAIN_LAM =1 AND ACTIVE_FLAG = 1 THEN 1 END), 
    REV4= COUNT(CASE WHEN QTR = 1 AND MAIN_JAC =1 AND ACTIVE_FLAG = 1 THEN 1 END) 
    FROM MyTable 

這個SELECT語句的結果是這樣的:

REV1 REV2 REV3 REV4 
12  45  87 54 

回答

0

嘗試這個

這將減少的條件和更清晰。

DECLARE @Rev1 int 
DECLARE @Rev2 int 
DECLARE @Rev3 int 
DECLARE @Rev4 int 
SELECT 
    @Rev1 = SUM(CASE WHEN MAIN_SAT =1 THEN 1 ELSE 0 END), 
    @Rev2= SUM(CASE WHEN MAIN_EKL =1 THEN 1 ELSE 0 END), 
    @Rev3= SUM(CASE WHEN MAIN_LAM =1 THEN 1 ELSE 0 END), 
    @Rev4= SUM(CASE WHEN MAIN_JAC =1THEN 1 ELSE 0 END) 
FROM MyTable 
WHERE QTR = 1 
    AND ACTIVE_FLAG = 1 
2

您可以做一個表變量或單個變量(根據您的喜好)。有獨立的變量例如:

DECLARE @Rev1 int 
DECLARE @Rev2 int 
DECLARE @Rev3 int 
DECLARE @Rev4 int 

SELECT 
@Rev1 = COUNT(CASE WHEN QTR = 1 AND MAIN_SAT =1 AND ACTIVE_FLAG = 1 THEN 1 END), 
@Rev2= COUNT(CASE WHEN QTR = 1 AND MAIN_EKL =1 AND ACTIVE_FLAG = 1 THEN 1 END), 
@Rev3= COUNT(CASE WHEN QTR = 1 AND MAIN_LAM =1 AND ACTIVE_FLAG = 1 THEN 1 END), 
@Rev4= COUNT(CASE WHEN QTR = 1 AND MAIN_JAC =1 AND ACTIVE_FLAG = 1 THEN 1 END) 
FROM MyTable 
相關問題