SQL将多行插入1:n表关联

时间:2014-07-03 11:58:23

标签: sql sql-server-2008 loops sql-server-2012

我有3个表(简化问题),如下所示:

Candidate
   - ID (primary key auto-numbered)
   - ProcessedOn
   - CandidateState

CandidateData
   - CandidateID
   - FieldKey
   - FieldValue

CandidateTransform
   - ID (primary key auto-numbered)
   - FieldKey 
   - FieldValue

CandidateTransform包含用于填充CandidateData的数据(即FieldKey - > FieldKey和FieldValue - > FieldValue)。 CandeidateTransform中的FieldValue包含一个SQL字符串,它从另一个数据库/表中选择FieldValue(人员信息),如下所示:

(SELECT firstName FROM Personnel WHERE id = @CandidateID)

之前我能够这样做,因为我们一次只处理一个候选者,我们将使用INSERT语句创建一个存储过程,如下所示:

DECLARE @NewCandidate TABLE (id bigint);

INSERT CloudRecruiting.Candidate (CandidateState, ActHdrKey, ActionProcessedOn, JobPostingID, Deleted)
OUTPUT INSERTED.CandidateKey INTO @NewCandidate
VALUES (0, 0, GETDATE(), @PlacementID, 0);

DECLARE @ID bigint;
SET @ID = (SELECT id FROM @NewCandidate);

DECLARE @CandidateID bigint;
SET @CandidateID = (SELECT candidate FROM Personnel WHERE id = @PlacementID);

INSERT INTO .CandidateData (CandidateKey, FieldKey, FieldValue) 
    VALUES (@ID, 1128, (SELECT ISNULL(LEFT(CONVERT(VARCHAR, dateOfBirth, 120), 10), '') FROM Personnel WHERE id = @CandidateID))
    , (@ID, 1159, (SELECT email FROM Personnel WHERE id = @CandidateID))
    , (@ID, 1284, (SELECT ssn FROM Personnel WHERE id = @CandidateID))
    , (@ID, 1303, CAST((SELECT payRate FROM Personnel WHERE id = @PlacementID) as nvarchar(MAX)))
    , (@ID, 1169, (SELECT firstName FROM Personnel WHERE id = @CandidateID))
    , (@ID, 1229, (SELECT middleName FROM Personnel WHERE id = @CandidateID))
    , (@ID, 1219, (SELECT lastName FROM Personnel WHERE id = @CandidateID))
    (etc.)

现在我们希望通过将SELECT语句存储在客户可以修改的表(CandidateTransform)中并且能够通过像这样的存储过程在一个批处理中处理多个候选来使该过程更加健壮(我们当前有SQL将捕获我们需要处理的CandidateID并将它们存储在tempTable中:

for each (candidateID in tempTable)
   create entry in Candidate
   capture new id number from Candidate

   for each (sql in CandidateTransform)
      execute sql script
      store value in CandidateData with the new id, FieldKey and FieldValue
   end
end

我没有使用SQL的while功能,也不确定这是否是最好的方法,或者是否有其他SQL可以用来做我需要的东西。任何解决方案都需要支持SQL 2008或更高版本。

0 个答案:

没有答案