Estoy realizando un procedimiento almacenado para saber las fechas futuras en las que se hace el mantenimiento de cada máquina, pero son muchas máquinas, necesito que tome como valor cada máquina y aplique el ciclo, pero sólo llama una máquina.
Los Declare que uso, son para que me llame los datos de la máquina para así poder realizar el ciclo y saber cuando sera el próximo mantenimiento dentro del rango de la fecha que le doy.
@name varchar(50),
@FechaHasta datetime,
@Result DATETIME = null OUTPUT)
AS
BEGIN
DECLARE @JOBNO NVARCHAR(50)
SELECT @JOBNO = JOBNO FROM PMMASTER INNER JOIN LABORMP
ON PMMASTER.PMID = LABORMP.PMID INNER JOIN PMMSCHEDULE
ON PMMASTER.PMID = PMMSCHEDULE.PMID
where EMPLOYEENAME = @name AND PMMSCHEDULE.CYCLETYPE =2 and PMMSCHEDULE.SETTING2 IS NOT NULL and PMMSCHEDULE.SETTING1 IS NOT NULL
DECLARE @DATELAST DATETIME
SELECT @DATELAST = DATELAST FROM PMMSCHEDULE INNER JOIN PMMASTER
ON PMMASTER.PMID = PMMSCHEDULE.PMID INNER JOIN LABORMP
ON PMMASTER.PMID = LABORMP.PMID
WHERE JOBNO in (@JOBNO) and EMPLOYEENAME =@name
DECLARE @SETTING1 INT
SELECT @SETTING1 = SETTING1 FROM PMMSCHEDULE INNER JOIN PMMASTER
ON PMMASTER.PMID = PMMSCHEDULE.PMID INNER JOIN LABORMP
ON PMMASTER.PMID = LABORMP.PMID
WHERE JOBNO in (@JOBNO) AND EMPLOYEENAME = @name
DECLARE @SETTING2 INT
SELECT @SETTING2 = SETTING2 FROM PMMSCHEDULE INNER JOIN PMMASTER
ON PMMASTER.PMID = PMMSCHEDULE.PMID INNER JOIN LABORMP
ON PMMASTER.PMID = LABORMP.PMID
WHERE JOBNO in (@JOBNO) AND EMPLOYEENAME = @name
DECLARE
@DateFirst INT
SELECT @DateFirst = @@DateFirst
/* Today */
DECLARE
@TodaysDate DATETIME
-- Finding today's date after resetting the time to midnight
SELECT @TodaysDate = CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 101), 101)
/* Todays WeekDay */
DECLARE
@TodaysWeekDay INT
SELECT @TodaysWeekDay = DATEPART(dw, @TodaysDate)
/* Selected WeekDay */
DECLARE
@WeekDay INT
SELECT @WeekDay = CHARINDEX('1', @Setting2)
/* Schedule Date */
DECLARE
@ScheduleDate DATETIME
-- Find the starting schedule date. If the schedule date is in a previous
-- week, adjust to the most recent week in the schedule
SELECT @ScheduleDate = @DATELAST
-- Adjust scheduled date to closest possible week day
SELECT @ScheduleDate = DATEADD(dd, @WeekDay - DATEPART(dw, @ScheduleDate), @ScheduleDate)
-- Add cycles until a possible date is met
WHILE (@ScheduleDate < @TodaysDate)
SELECT @ScheduleDate = DATEADD(wk, @Setting1, @ScheduleDate)
IF (@ScheduleDate <= @DATELAST)
SELECT @ScheduleDate = DATEADD(wk, @Setting1, @ScheduleDate)
SELECT @Result = @ScheduleDate
SELECT @Result AS RESULTADO
SET DATEFIRST @DateFirst
WHILE(@Result <@FechaHasta)
BEGIN
IF(@Result <@FechaHasta)
SELECT @Result = DATEADD(WK, @Setting1, @Result)
SET IDENTITY_INSERT [00TblFecha] ON
INSERT INTO dbo.[00TblFecha](idFecha,jobno,fecha)VALUES(3,@JOBNO,@Result)
SET IDENTITY_INSERT[00TblFecha] OFF
print @Result
end