2016-05-25 82 views
0

我有一個輸出正確信息的FETCH查詢,但它通過提取輸出每個循環作爲輸出的單獨查詢。將多個查詢合併爲單個多行輸出

什麼我希望做的是將結果輸出到一個表(或在我的情況下,我最終將建立與此查詢視圖)

DECLARE @THID Cursor 
DECLARE @THIDValue int 

SET @THID = CURSOR FOR 
    SELECT  
     Transheader.ID 
    FROM    
     TransHeader WITH (nolock) 
    INNER JOIN 
     TransHeaderUserField WITH (nolock) ON TransHeader.ID = TransHeaderUserField.ID 
    WHERE   
     (TransHeaderUserField.Rework = '1') 
     AND TransHeader.ID IS NOT NULL 

OPEN @THID 

FETCH NEXT FROM @THID INTO @THIDValue 

WHILE @@FETCH_STATUS = 0 
BEGIN 
    SELECT   
     (SELECT 
      SUM(totPartCost) 
     FROM 
      TransDetail 
     WHERE 
      TransHeaderID = @THIDValue) AS ThePartCost, 
     TransHeader.OrderNumber, TransHeader.ClassTypeID, 
     TransHeader.OrderCreatedDate, TransHeaderUserField.Rework, 
     TransHeaderUserField.Rework_Type, 
     TransHeaderUserField.Rework_Orders, TransHeaderUserField.Rework_Employee, 
     TransHeaderUserField.Rework_Department, TransHeader.Description 
    FROM    
     TransHeader WITH (nolock) 
    INNER JOIN 
     TransHeaderUserField WITH (nolock) ON TransHeader.ID = TransHeaderUserField.ID 
    WHERE   
     (TransHeaderUserField.Rework = '1') AND TransHeader.ID = @THIDValue 
    ORDER BY 
     TransHeaderUserField.Rework_Department, TransHeaderUserField.Rework_Employee 

    FETCH NEXT FROM @THID INTO @THIDValue 
END 

CLOSE @THID 
DEALLOCATE @THID 

enter image description here

+1

設置[壞習慣踢 - 把NOLOCK無處不在](http://blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere/) - 不建議(根本不要)在任何地方使用它 - 恰恰相反! –

回答

1

將每個選擇到臨時表中,並且在完成循環的所有迭代後,從臨時表中選擇*。