我正在寻找一种循环SQL表并将其与另一个表进行比较的方法,如果两个列值匹配,则更新一个表中的记录。
我有两个表HplcData
和DeSchedule
,Deschedule
包含HplcData
表将具有的所有未来记录。我想要一个SQL查询,它将在HplcData
中查找Deschedule
表中的匹配记录,如果有Deschedule
中的记录更新来自HplcData
的数据,完成标记。通过具有相同的BatchId
和SampleAge
来定义匹配。
我怎样才能完成这个?
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
所以截至目前我有一个触发器可以做到这一点,但是我需要一种方法来协调数据,如果触发器错过了一个记录,我将运行这个查询是一个Windows工作。
这是我目前用于触发的查询:
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 :(得分: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;
答案 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