Lavoriamo su un'applicazione che visualizza un elenco di ruoli e anche altre cose correlate a DateTime.
Quindi il mio database è pieno di relazioni come in questo piccolo esempio:
Ne risulta un grande StoredProcedure per ottenere tutti i dati dei dipendenti e i relativi dati relativi alla data per una determinata combinazione di dipendente, giorno, mese, anno
che appare come questo (basato sull'Esempio):
ALTER PROCEDURE Mitarbeiter_Select
@myDate AS datetime2(7) = null, -- null represent current
@EmployeeId AS int = null -- null represents all Employees
AS
-- declare my intern parameters
DECLARE @oldDate AS datetime2(7)= null;
SET @Wann = ISNULL(@Wann,GETDATE());
-- set the previous month
SET @oldDate= DATEADD(month, -1, @Wann); -- for some calculations i need information from the month before
--############################# REGION TEMP TABLE ###########################
-- create my TempTable
create table #EmployeeToFind
(
ID int,
FirstName nvarchar(MAX),
LastName nvarchar(MAX)
)
create table #EmployeeVacationDays
(
RefEmployeeId int,
YearDays int
)
create table #EmployeeManager
(
RefEmployeeId int,
IsManager bit
)
--############################# REGION FILL TABLE ###########################
INSERT INTO #EmployeeToFind
SELECT ID,
Personalnummer,
FirstName ,
LastName
FROM Employee
WHERE ID = ISNULL(@EmployeeId, ID)
INSERT INTO #EmployeeVacationDays
SELECT RefEmployeeId ,
Days AS YearDays
FROM VacationDays OUTERMU
WHERE RefEmployeeId = ISNULL(@EmployeeId, RefEmployeeId )
AND ValidAfter = (
SELECT MAX(ValidAfter )
FROM VacationDays
WHERE RefEmployeeId = OUTERMU.RefEmployeeId
AND ( YEAR(ValidAfter) = YEAR(@Wann)
OR
YEAR(ValidAfter) < YEAR(@Wann)
)
)
INSERT INTO #EmployeeManager
SELECT RefEmployeeId ,
IsManager
FROM Manager
WHERE RefEmployeeId = ISNULL(@EmployeeId, RefEmployeeId )
AND ValidAfter = (
SELECT MAX(ValidAfter )
FROM Manager
WHERE RefEmployeeId = OUTERMA.RefEmployeeId
AND ( YEAR(ValidAfter) = YEAR(@Wann) AND MONTH(ValidAfter) <= MONTH(@Wann)
OR
YEAR(ValidAfter) < YEAR(@Wann)
)
)
--############################# REGION RESULT SELECT ###########################
SELECT #EmployeeToFind.ID,
#EmployeeToFind.FirstName ,
#EmployeeToFind.LastName ,
#EmployeeVacationDays.YearDays ,
#EmployeeManager.IsManager ,
-- in our real Procedure we have here also some CASE WHEN ... THEN ... ELSE ... END
-- Depending on IS NULL/ IS NOT NULL of some Values
FROM #EmployeeToFind
left outer join #EmployeeVacationDayson #EmployeeToFind.ID= #EmployeeVacationDays.RefEmployeeId
left outer join #EmployeeManageron #EmployeeToFind.ID= #EmployeeManager.RefEmployeeId
Ora la mia domanda è un modo per semplificare questo?