Placement table
CREATE TABLE [dbo].[Stage]( [Name] [varchar](50) NULL, [Street] [varchar](50) NULL, [State] [varchar](50) NULL, [pkAddressID] [int] NULL ) ON [PRIMARY] GO
Address table
CREATE TABLE [dbo].[Address]( [pkAddressID] [int] IDENTITY(1,1) NOT NULL, [street] [varchar](50) NULL, [state] [varchar](50) NULL ) ON [PRIMARY]
- Employee table
CREATE TABLE [dbo].[Employee]( [pkEmployeeID] [int] IDENTITY(1,1) NOT NULL, [fkAddressID] [int] NULL, [Name] [varchar](50) NULL ) ON [PRIMARY] GO
--- DFT - Loading data into a Stage table
--- Executing SQL task 1 --- Filling the address table
Merge [dbo].[Address] as target using ( select distinct [Street], [State] from [dbo].[Stage] ) as source on source.[Street] = target.[Street] and source.[State] = target.[State] when not matched then insert ([Street], [State]) values (source.[Street], source.[State]) ;
--- Executing SQL task 2 --- Populating the Stage table // column pkAddressID
Merge [dbo].[Stage] as target using ( select [pkAddressID],[Street], [State] from [1Address] ) as source on source.[Street] = target.[Street] and source.[State] = target.[State] when matched then update set target.[pkAddressID] = source.[pkAddressID] ;
--- Execution of the SQL task 3 --- Filling the employee table
Merge [dbo].[Employee] as target using ( select [pkAddressID], [Name] from [dbo].[1Stage] ) as source on source.[pkAddressID] = target.[fkAddressID] and source.[Name] = target.[Name] when not matched then insert ([fkAddressID], [Name]) values (source.[pkAddressID], source.[Name]) ;