Integration.GetEmployeeUpdates
Documentation | WideWorldImporters |
Schema | Integration |
Name | GetEmployeeUpdates |
Input/Output
Mode | Name | Data type | Description | |
---|---|---|---|---|
1 | IN | LastCutoff | datetime2(7) | |
2 | IN | NewCutoff | datetime2(7) |
Script
CREATE PROCEDURE Integration.GetEmployeeUpdates @LastCutoff datetime2(7), @NewCutoff datetime2(7) WITH EXECUTE AS OWNER AS BEGIN SET NOCOUNT ON; SET XACT_ABORT ON; DECLARE @EndOfTime datetime2(7) = '99991231 23:59:59.9999999'; CREATE TABLE #EmployeeChanges ( [WWI Employee ID] int, Employee nvarchar(50), [Preferred Name] nvarchar(50), [Is Salesperson] bit, Photo varbinary(max), [Valid From] datetime2(7), [Valid To] datetime2(7) ); DECLARE @PersonID int; DECLARE @ValidFrom datetime2(7); -- need to find any employee changes that have occurred, including during the initial load DECLARE EmployeeChangeList CURSOR FAST_FORWARD READ_ONLY FOR SELECT p.PersonID, p.ValidFrom FROM [Application].People_Archive AS p WHERE p.ValidFrom > @LastCutoff AND p.ValidFrom <= @NewCutoff AND p.IsEmployee <> 0 UNION ALL SELECT p.PersonID, p.ValidFrom FROM [Application].People AS p WHERE p.ValidFrom > @LastCutoff AND p.ValidFrom <= @NewCutoff AND p.IsEmployee <> 0 ORDER BY ValidFrom; OPEN EmployeeChangeList; FETCH NEXT FROM EmployeeChangeList INTO @PersonID, @ValidFrom; WHILE @@FETCH_STATUS = 0 BEGIN INSERT #EmployeeChanges ([WWI Employee ID], Employee, [Preferred Name], [Is Salesperson], Photo, [Valid From], [Valid To]) SELECT p.PersonID, p.FullName, p.PreferredName, p.IsSalesperson, p.Photo, p.ValidFrom, p.ValidTo FROM [Application].People FOR SYSTEM_TIME AS OF @ValidFrom AS p WHERE p.PersonID = @PersonID; FETCH NEXT FROM EmployeeChangeList INTO @PersonID, @ValidFrom; END; CLOSE EmployeeChangeList; DEALLOCATE EmployeeChangeList; -- add an index to make lookups faster CREATE INDEX IX_EmployeeChanges ON #EmployeeChanges ([WWI Employee ID], [Valid From]); -- work out the [Valid To] value by taking the [Valid From] of any row that's for the same entry but later -- otherwise take the end of time UPDATE cc SET [Valid To] = COALESCE((SELECT MIN([Valid From]) FROM #EmployeeChanges AS cc2 WHERE cc2.[WWI Employee ID] = cc.[WWI Employee ID] AND cc2.[Valid From] > cc.[Valid From]), @EndOfTime) FROM #EmployeeChanges AS cc; SELECT [WWI Employee ID], Employee, [Preferred Name], [Is Salesperson], Photo, [Valid From], [Valid To] FROM #EmployeeChanges ORDER BY [Valid From]; DROP TABLE #EmployeeChanges; RETURN 0; END; |
Exported: 2019-02-04 23:04, Last imported: 2018-08-10 09:51