IF NOT OBJECT_ID('V_EST_ALCADA_CP_PED_ALCADAS_TOKEN') IS NULL
	BEGIN 
		DROP VIEW V_EST_ALCADA_CP_PED_ALCADAS_TOKEN
	END
	
GO	


CREATE VIEW V_EST_ALCADA_CP_PED_ALCADAS_TOKEN
AS 	
	
		SELECT A.CD_CTR, A.CD_IT, A.CD_USU, A.ID_TOKEN, 0 AS TP_LIB_CANCEL
		FROM EST_ALCADA_CP_PED_ALCADAS A
			INNER JOIN EST_ALCADA_CP_PED_PEND PEND ON 
				A.CD_CTR = PEND.CD_CTR
			LEFT JOIN EST_ALCADA_CP_PED_ALCADAS_LIB LIB ON 
				A.CD_CTR = LIB.CD_CTR
				AND A.CD_IT = LIB.CD_IT
			LEFT JOIN EST_ALCADA_CP_PED_ALCADAS_CANCEL CANCEL ON 
				A.CD_CTR = CANCEL.CD_CTR
				AND A.CD_IT = CANCEL.CD_IT			
		WHERE 
			LIB.CD_CTR IS NULL
			AND CANCEL.CD_CTR IS NULL
		UNION ALL 

		SELECT A.CD_CTR, A.CD_IT, A.CD_USU, A.ID_TOKEN_CANCEL, 1 AS TP_LIB_CANCEL
		FROM EST_ALCADA_CP_PED_ALCADAS A
			INNER JOIN EST_ALCADA_CP_PED_PEND PEND ON 
				A.CD_CTR = PEND.CD_CTR
			LEFT JOIN EST_ALCADA_CP_PED_ALCADAS_LIB LIB ON 
				A.CD_CTR = LIB.CD_CTR
				AND A.CD_IT = LIB.CD_IT
			LEFT JOIN EST_ALCADA_CP_PED_ALCADAS_CANCEL CANCEL ON 
				A.CD_CTR = CANCEL.CD_CTR
				AND A.CD_IT = CANCEL.CD_IT	
		WHERE 
			LIB.CD_CTR IS NULL
			AND CANCEL.CD_CTR IS NULL		
			

GO	