﻿-- =============================================
-- Description:	Törli az egy hétnél régebbi fel nem használt linkeket, valamint a hozzájuk tartozó CSÖKKENTETT jogosultságú gondviselőket
-- =============================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


IF OBJECT_ID('[dbo].[uspDeleteInvalidLinks]') IS NOT NULL 
BEGIN
  DROP PROCEDURE [dbo].[uspDeleteInvalidLinks]
END  
GO


CREATE PROCEDURE [dbo].[uspDeleteInvalidLinks]
	
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
	SET NOCOUNT ON;
	
CREATE TABLE #DeletedIds ( ID INT );

DELETE FROM T_JELSZOMODOSITASLINK
OUTPUT DELETED.C_GONDVISELOID INTO #DeletedIds
WHERE (GETDATE() - 7) > C_LETREHOZASDATUMA
  AND TOROLT = 'F'

UPDATE e
SET e.TOROLT = 'T'
FROM T_EMAIL e
INNER JOIN #DeletedIds gId ON gId.ID = e.C_GONDVISELOID
INNER JOIN T_GONDVISELO g ON g.ID = gId.ID AND g.C_ISCSOKKENTETTGONDVISELO = 'T'
WHERE e.TOROLT = 'F'
  AND NOT EXISTS (SELECT 1 FROM T_FELHASZNALOBELEPES x WHERE g.ID = x.C_GONDVISELOID AND x.TOROLT = 'F')
  AND NOT EXISTS (SELECT 1 FROM T_JELSZOMODOSITASLINK x WHERE g.ID = x.C_GONDVISELOID AND x.TOROLT = 'F')

UPDATE c
SET c.TOROLT = 'T'
FROM T_CIM c
INNER JOIN #DeletedIds gId ON gId.ID = c.C_GONDVISELOID
INNER JOIN T_GONDVISELO g ON g.ID = gId.ID AND g.C_ISCSOKKENTETTGONDVISELO = 'T'
WHERE c.TOROLT = 'F'
  AND NOT EXISTS (SELECT 1 FROM T_FELHASZNALOBELEPES x WHERE g.ID = x.C_GONDVISELOID AND x.TOROLT = 'F')
  AND NOT EXISTS (SELECT 1 FROM T_JELSZOMODOSITASLINK x WHERE g.ID = x.C_GONDVISELOID AND x.TOROLT = 'F')
  
UPDATE g
SET g.TOROLT = 'T'
FROM T_GONDVISELO g
INNER JOIN #DeletedIds d ON d.ID = g.ID
WHERE g.C_ISCSOKKENTETTGONDVISELO = 'T'
  AND g.TOROLT = 'F'
  AND NOT EXISTS (SELECT 1 FROM T_FELHASZNALOBELEPES x WHERE g.ID = x.C_GONDVISELOID AND x.TOROLT = 'F')
  AND NOT EXISTS (SELECT 1 FROM T_JELSZOMODOSITASLINK x WHERE g.ID = x.C_GONDVISELOID AND x.TOROLT = 'F')

DROP TABLE #DeletedIds
	
END
GO

