복붙노트

[SQL] 부모와 자식 테이블에 데이터 삽입 - T-SQL

SQL

부모와 자식 테이블에 데이터 삽입 - T-SQL

암호:

CREATE TYPE dbo.tEmployeeData AS TABLE 
(
     FirstName NVARCHAR(50),
     LastName NVARCHAR(50),
     DepartmentType NVARCHAR(10),
     DepartmentBuilding NVARCHAR(50),
     DepartmentEmployeeLevel NVARCHAR(10),
     DepartmentTypeAMetadata NVARCHAR(100),
     DepartmentTypeBMetadata NVARCHAR(100)
)
GO

CREATE PROC dbo.EmployeeImport 
    (@tEmployeeData tEmployeeData READONLY)
AS
BEGIN
     DECLARE @MainEmployee TABLE 
                           (EmployeeID INT IDENTITY(1,1),
                            FirstName NVARCHAR(50),
                            LastName NVARCHAR(50))

    DECLARE @ParentEmployeeDepartment TABLE 
                                      (EmployeeID INT,
                                       ParentEmployeeDepartmentID INT IDENTITY(1,1),
                                       DepartmentType NVARCHAR(10))

    DECLARE @ChildEmployeeDepartmentTypeA TABLE 
                  (ParentEmployeeDepartmentID INT,
                   DepartmentBuilding NVARCHAR(50),
                   DepartmentEmployeeLevel NVARCHAR(10),
                   DepartmentTypeAMetadata NVARCHAR(100))

    DECLARE @ChildEmployeeDepartmentTypeB TABLE 
                  (ParentEmployeeDepartmentID INT,
                   DepartmentBuilding NVARCHAR(50),
                   DepartmentEmployeeLevel NVARCHAR(10),
                   DepartmentTypeBMetadata NVARCHAR(100))

    -- INSERT CODE GOES HERE
    SELECT * FROM @MainEmployee
    SELECT * FROM @ParentEmployeeDepartment
    SELECT * FROM @ChildEmployeeDepartmentTypeA
    SELECT * FROM @ChildEmployeeDepartmentTypeB
END
GO

DECLARE @tEmployeeData tEmployeeData

INSERT INTO @tEmployeeData (FirstName, LastName, DepartmentType,
                            DepartmentBuilding, DepartmentEmployeeLevel,
                            DepartmentTypeAMetadata, DepartmentTypeBMetadata)
    SELECT  
        N'Tom_FN', N'Tom_LN', N'A',
        N'101', N'IV', N'Tech/IT', NULL
    UNION
    SELECT  
        N'Mike_FN', N'Mike_LN', N'B',
        N'OpenH', N'XII', NULL, N'Med' 
    UNION
    SELECT  
        N'Joe_FN', N'Joe_LN', N'A',
        N'101', N'IV', N'Tech/IT', NULL
    UNION
    SELECT  
        N'Dave_FN', N'Dave_LN', N'B',
        N'OpenC', N'XII', NULL, N'Lab' 

    EXEC EmployeeImport @tEmployeeData
GO

DROP PROC dbo.EmployeeImport 
DROP TYPE dbo.tEmployeeData

노트:

골:

산출:

@ Menmploi :

EmployeeID  FirstName   LastName
---------------------------------
1           Tom_FN      Tom_LN
2           Mike_FN     Mike_LN
3           Joe_FN      Joe_LN
4           Dave_FN     Dave_LN

@ParentEmployeeDepartment :

EmployeeID  ParentEmployeeDepartmentID  DepartmentType
-------------------------------------------------------
1           1                           A
2           2                           B
3           3                           A
4           4                           B

@ChildEmployeeDepartmentTypeA :

ParentEmployeeDepartmentID  DepartmentBuilding  DepartmentEmployeeLevel DepartmentTypeAMetadata
---------------------------------------------------------------------------------------------------------
1                           101                 IV                      Tech/IT
3                           101                 IV                      Tech/IT

@ChildEmployeeDepartmentTypeB :

ParentEmployeeDepartmentID  DepartmentBuilding  DepartmentEmployeeLevel DepartmentTypeAMetadata
----------------------------------------------------------------------------------------------------------
2                           OpenH               XII                     Med
4                           OpenC               XII                     Lab

내가 삽입 및 GET 직원 ID 및 ParentEmployeeDepartmentID 후 OUTPUT 절을 사용할 수 있습니다 알고 있지만, 나는 확실히 부모 테이블에 바로 매핑 잘 작성 테이블에 올바른 자식 레코드를 삽입하는 방법을 모르겠어요. 어떤 도움을 주시면 감사하겠습니다.

해결법

  1. ==============================

    1.여기에 (내가 코멘트에 연결 한 같은 답변에 따라) 내 솔루션입니다 :

    여기에 (내가 코멘트에 연결 한 같은 답변에 따라) 내 솔루션입니다 :

    첫째, 당신은 직원을위한 임시 ID를 개최, 당신의 UDT에 다른 열을 추가해야합니다 :

    CREATE TYPE dbo.tEmployeeData AS TABLE 
    (
         FirstName NVARCHAR(50),
         LastName NVARCHAR(50),
         DepartmentType NVARCHAR(10),
         DepartmentBuilding NVARCHAR(50),
         DepartmentEmployeeLevel NVARCHAR(10),
         DepartmentTypeAMetadata NVARCHAR(100),
         DepartmentTypeBMetadata NVARCHAR(100),
         EmployeeId int
    )
    GO
    

    그 새로운 employeeId를 열으로 채우기 :

    DECLARE @tEmployeeData tEmployeeData
    
    INSERT INTO @tEmployeeData (FirstName, LastName, DepartmentType,
                                DepartmentBuilding, DepartmentEmployeeLevel,
                                DepartmentTypeAMetadata, DepartmentTypeBMetadata, EmployeeId)
    SELECT  
        N'Tom_FN', N'Tom_LN', N'A',
        N'101', N'IV', N'Tech/IT', NULL, 5
    UNION
    SELECT  
        N'Mike_FN', N'Mike_LN', N'B',
        N'OpenH', N'XII', NULL, N'Med', 6
    UNION
    SELECT  
        N'Joe_FN', N'Joe_LN', N'A',
        N'101', N'IV', N'Tech/IT', NULL, 7
    UNION
    SELECT  
        N'Dave_FN', N'Dave_LN', N'B',
        N'OpenC', N'XII', NULL, N'Lab', 8
    

    그런 다음 프로 시저에 전송되는 데이터의 임시 직원 ID에 대한 직원 테이블에서 삽입 된 값을 매핑 테이블 변수를 사용 :

    DECLARE @EmployeeidMap TABLE
    (
        temp_id int,
        id int
    )
    

    이제 트릭을 사용하면 출력 절에 모두 삽입 및 소스 데이터에서 값을 사용하기 때문에 SELECT ... 대신 INSERT의 MERGE 문을 사용하여 직원 테이블을 채우는 것입니다 :

    MERGE INTO @MainEmployee USING @tEmployeeData AS sourceData ON 1 = 0 -- Always not matched
    WHEN NOT MATCHED THEN
    INSERT (FirstName, LastName)
    VALUES (sourceData.FirstName, sourceData.LastName)
    OUTPUT sourceData.EmployeeId, inserted.EmployeeID 
    INTO @EmployeeidMap (temp_id, id); -- populate the map table
    

    그것의 간단한에 그 시점에서, 당신은 당신이 실제 employeeId를 얻을 수있는 @EmployeeidMap로 전송되는 데이터에 가입해야합니다 :

    INSERT INTO @ParentEmployeeDepartment (EmployeeID, DepartmentType)
    SELECT Id, DepartmentType
    FROM @tEmployeeData 
    INNER JOIN @EmployeeidMap ON EmployeeID = temp_id
    

    이제 당신은 당신이 보낸 데이터에 ParentEmployeeDepartmentID의 실제 값을 매핑 할 @ParentEmployeeDepartment의 데이터를 사용할 수 있습니다 :

    SELECT FirstName,
         LastName,
         SentData.DepartmentType As [Dept. Type],
         DepartmentBuilding As Building,
         DepartmentEmployeeLevel As [Emp. Level],
         DepartmentTypeAMetadata As [A Meta],
         DepartmentTypeBMetadata As [B Meta],
         SentData.EmployeeId As TempId, EmpMap.id As [Emp. Id], DeptMap.ParentEmployeeDepartmentID As [Dept. Id]
    FROM @tEmployeeData SentData
    INNER JOIN @EmployeeidMap EmpMap ON SentData.EmployeeId = temp_id 
    INNER JOIN @ParentEmployeeDepartment DeptMap ON EmpMap.id = DeptMap.EmployeeID
    

    결과 :

    FirstName   LastName    Dept. Type  Building    Emp. Level  A Meta      B Meta  TempId      Emp. Id     Dept. Id
    ---------   --------    ----------  --------    ----------  ------      ------  ------      ----------- -----------
    Dave_FN     Dave_LN     B           OpenC       XII         NULL        Lab     8           1           1
    Joe_FN      Joe_LN      A           101         IV          Tech/IT     NULL    7           2           2
    Mike_FN     Mike_LN     B           OpenH       XII         NULL        Med     6           3           3
    Tom_FN      Tom_LN      A           101         IV          Tech/IT     NULL    5           4           4
    

    나는이 시점에서 당신은 쉽게 마지막이 개 삽입 자신을 알아낼 수 있다고 확신합니다.

  2. from https://stackoverflow.com/questions/38213008/t-sql-insert-data-into-parent-and-child-tables by cc-by-sa and MIT license