2011-10-31 38 views
0

我試圖根據相關表中的查詢結果更新一個表中的大量記錄。在這個例子中,我在tbl_events中有150條記錄,我想用「entered_by」進行更新,爲了獲得這150條記錄,我需要將選擇與tbl_locations中的150條記錄匹配,其值爲「needs update」筆記字段。 「Entered_by」值不存在於tbl_locations中,我只是試圖根據關係前提更新表。但我得到以下錯誤:在一個表中滿足相關表的查詢結果的SQL更新記錄

UPDATE TBL_EVENTS 
SET Entered_By = 'Fred' 
FROM GRSTBL_EVENTS as sp 
JOIN TBL_LOCATIONS as so 
On sp.Location_ID = so.Location_ID 
    AND so.Notes =(SELECT Notes from TBL_LOCATIONS where Notes = 'needs update') 

Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.

回答

0

如果我理解你的數據結構正確,那麼你需要是否有相關tbl_locations表中的任何票據,以更新entered_by領域。

如果是這樣那麼下面,這就是所謂的correlated subquery應該做你想要

UPDATE TBL_EVENTS 
SET Entered_By = 'Fred' 
WHERE EXISTS (
    SELECT 1 
    FROM TBL_LOCATIONS 
    WHERE TBL_LOCATIONS.Location_ID = TBL_EVENTS.Location_ID 
    AND TBL_LOCATIONS.Notes = 'needs update' 
) 
1

您可以在

UPDATE TBL_EVENTS 
SET Entered_By = 'Fred' 
FROM GRSTBL_EVENTS as sp 
JOIN TBL_LOCATIONS as so 
On sp.Location_ID = so.Location_ID 
AND so.Notes in (SELECT Notes from TBL_LOCATIONS where Notes = 'needs update') 
+0

+1用什麼似乎比史蒂夫Weet的使用'那裏存在簡單' –

+0

這個IN子句與'so.Notes ='需要更新'有什麼不同? –

相關問題