创建将数据从一个临时表插入或更新到其他4个表的过程

时间:2018-01-17 09:11:32

标签: sql-server database stored-procedures sqlbulkcopy

我需要 创建

的程序
  1. 将源表中的数据插入或更新到target1表
  2. 将数据插入target2表并将获得插入的ID 来自target1,target2 tables
  3. 将它们插入目标表3
  4. 将target1.ID插入target4表
  5. 源表是一个临时表,我使用批量复制将大数据插入到该表中,然后将数据移动到目标表以获得性能。

    MSPCompanies - insert or update по признаку INN
    MSPDownloads insert
    MSPAccepted insert MSPCompanies.ID и MSPDownloads.ID
    MSPAcceptedNow insert MSPCompanies.ID
    

    在MSPCompanies中插入或更新我使用MERGE

    BEGIN
     BEGIN TRY
      BEGIN TRANSACTION
     -- SET NOCOUNT ON added to prevent extra result sets from
     -- interfering with SELECT statements.
     SET NOCOUNT ON;
    
        -- Insert statements for procedure here
     MERGE INTO [MSPCompanies] AS [Target]
    USING [MSPTempTable] AS [Source]
     ON Target.INN = Source.INN
    WHEN MATCHED THEN
    UPDATE SET 
     Target.Name = Source.Name,
     Target.ShortName = Source.ShortName,
     Target.FIO = Source.FIO,
     Target.SubjectType = Source.SubjectType,
     Target.SubjectCategory = Source.SubjectCategory,
     @MSPCompaniesId = Target.MSP_Companies_ID
    
    WHEN NOT MATCHED THEN
    INSERT 
     (INN, Name, ShortName, FIO, SubjectType, SubjectCategory) 
    VALUES 
     (Source.INN, Source.Name, Source.ShortName, Source.FIO, Source.SubjectType, Source.SubjectCategory);
    
    IF @MSPCompaniesId IS NULL
    BEGIN
        SET @MSPCompaniesId = CAST(SCOPE_IDENTITY() as [int]);
    END
    SELECT @MSPCompaniesId
    --BEGIN
    INSERT INTO dbo.MSPAcceptedNow
    (MSP_Company_ID)
    VALUES(@MSPCompaniesId)
    

    但看起来似乎无法使用其他三个表进行其他操作,并尝试使用insert-update进行操作,但无论如何都无法做到。

    BEGIN TRANSACTION MoveDataFromMSPTempTableT; 
    UPDATE t
        SET 
      Name = s.Name,
      ShortName = s.ShortName,
      FIO = s.FIO,
      SubjectType = s.SubjectType,
      SubjectCategory = s.SubjectCategory
        FROM MSPCompanies t
            JOIN MSPTempTable s
            ON s.INN = t.INN;
    
    INSERT INTO MSPCompanies
            SELECT s.INN,
                   s.Name,
          s.ShortName,
          s.FIO,
          s.SubjectType,
          s.SubjectCategory
                FROM MSPTempTable s
                    LEFT JOIN MSPCompanies t
                    ON s.INN = t.INN
                WHERE t.INN IS NULL;
    
    COMMIT TRANSACTION MoveDataFromMSPTempTableT;
    

    谢谢。

1 个答案:

答案 0 :(得分:0)

您无法使用变量跟踪所有更改,但可以使用OUTPUT跟踪所有更改。

<style>
.txtArea{
    overflow:auto;
    height:100px;
    width:500px;
    -moz-transform: scale(0.9);
    -webkit-transform: scale(0.9);
    -o-transform: scale(0.9);
    transform: scale(0.9);
}
</style>
<textarea class="txtArea">
</textarea>