简体   繁体   中英

Temp table and insert the unique Ids into another table, with SQL-Server

How to loop through the temp table and insert the unique Ids into another table?

SELECT Id
INTO #TempSubjectValues
FROM WebPortalDemo2DB_Dev_November.dbo.Subject_Value
WHERE SubjectId = @SubjectID_Latest
    
DECLARE @i INT
    
SELECT @i = min(Id)
FROM #TempSubjectValues
    
DECLARE @max INT
    
SELECT @max = max(Id)
FROM #TempSubjectValues
    
WHILE @i <= @max
BEGIN
     INSERT INTO WebPortalDemo2DB_Dev_November.dbo.SubjectValueDetails (
     [Value_Name]
     ,[Value_Details]
     ,[ParentValueDetailId]
     ,[Subject_ValueId]
     ,[isDeleted]
     ,[DeletedDate]
     ,[DeletedBy]
     )
SELECT [Value_Name]
      ,[Value_Details]
      ,[ParentValueDetailId]
      ,@i
      ,[isDeleted]
      ,[DeletedDate]
      ,[DeletedBy]
FROM SubjectValueDetails
WHERE Subject_ValueId IN (
                        SELECT Id
                        FROM Subject_Value
                        WHERE SubjectId = @SubjectID
                        )
    
SET @i = @i + 1
END

This loop inserts duplicate data but what I want is to insert records that It picks in select statement but the [Subject_ValueId] shall be the one that has been inserted into the Subject_Value table which I am already storing in the temp table.

The reason is that we need the new primary key of parent if we are inserting while picking from another table and database.

Not sure if this going to work without sample data. Uncomment the line for the insert once you are sure the select results are correct.

--  INSERT INTO WebPortalDemo2DB_Dev_November.dbo.SubjectValueDetails 
SELECT  DISTINCT
        [Value_Name]            =   SVD.[Value_Name]
     ,  [Value_Details]         =   SVD.[Value_Details]
     ,  [ParentValueDetailId]   =   SVD.[ParentValueDetailId]
     ,  [Subject_ValueId]       =   SVD.ID
     ,  [isDeleted]             =   SVD.[isDeleted]
     ,  [DeletedDate]           =   SVD.[DeletedDate]
     ,  [DeletedBy]             =   SVD.[DeletedBy]

FROM    SubjectValueDetails                             SVD
JOIN    WebPortalDemo2DB_Dev_November.dbo.Subject_Value SVN ON  SVN.SubjectID   =   SVD.ID
JOIN    Subject_Value                                   SV  ON  SV.ID           =   SVD.Subject_ValueId

WHERE   
        SV.SubjectId    =   @SubjectID          --  IDK where this value come from
    AND SVN.SubjectId   =   @SubjectID_Latest   --  IDK where this value come from

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM