2016-11-10 67 views
-1

我正在尋找一種方法來循環訪問一個SQL表並將它與另一個表進行比較,如果兩個列值匹配,則更新一個表中的記錄。如何查找SQL中的匹配記錄,如果發現然後更新

我有兩個表HplcDataDeSchedule,Deschedule具有HplcData表將具有的所有未來記錄。我想要一個SQL查詢,該查詢將在HplcData中查找Deschedule表中的匹配記錄,並且如果更新Deschedule中的記錄與來自HplcData的數據並且標記完成。通過具有相同的BatchIdSampleAge來定義匹配。

我該如何做到這一點?

Hplc Data 

BatchID | SampleAge | Ethanol | Glucose 
7254  20   7.8  4.5 

DeSchedule 

BatchID | SampleAge | Ethanol | Glucose | SampleCompleted 
7254  20   Null  Null  Null 
7254  30   Null  Null  Null 

所以截至目前我有一個觸發器,做到這一點,但我需要一個方式,如果觸發錯過了記錄調和的數據,我將運行此查詢是一個窗口的工作。

這是我目前使用的觸發查詢:

ALTER TRIGGER [dbo].[Trigger_HPLC_update_details_DeSchedule] ON [dbo].[HplcData] 
    AFTER INSERT 
AS 
BEGIN 
    DECLARE @BatchId int, @Ethanol varchar(10), @Glucose varchar(10), @SampleAge varchar(10); 
    SELECT @BatchId = bd.[BatchID],@Ethanol = [Ethanol], @Glucose= [DP1Glucose], @SampleAge = bd.SampleAge 
    from INSERTED bd 
    update [dbo].[DeSchedule] SET [Ethanol] = @Ethanol, [Glucose] = @Glucose, [SampleCompleted] = 1 
    WHERE [BatchID] = @BatchId AND [SampleAge] = @SampleAge 
END 
+0

[SQL更新從一個表到另一基於一個ID匹配](HTTP的可能的複製:// stackoverflow.com/questions/224732/sql-update-from-one-table-to-another-based-on-a-id-match) – xQbert

回答

1

您可以使用MERGE語句。

沿東西:

MERGE INTO dbo.DeSchedule as Target USING (dbo.HplcData) as Source 
ON Source.BatchID = Target.BatchID and Source.SampleAge = Target.SampleAge 
WHEN MATCHED 
UPDATE Ethanol = source.Ethanol, Glucose = source.Glucose, SampleCompleted = 1; 
0

使用在可能重複的鏈接:

UPDATE DeSchedule A 
SET A.Ethanol = HP.Ethanol, 
    A.Glucose = HP.Glucose 
FROM HPLCdata HP 
INNER JOIN DeSchedule DS 
    on HP.BatchID = DS.BatchID 
    and HP.SampleAge = DS.SampleAge 
相關問題