IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EST_NF_ENT_PRE_ENTRADA_PENDENCIA]') AND type in (N'U'))
begin

CREATE TABLE [dbo].[EST_NF_ENT_PRE_ENTRADA_PENDENCIA](
	[CD_EMP] [int] NOT NULL,
	[CD_CTR_PRE_ENTRADA] [int] NOT NULL,
	[DT_CAD] [datetime] NOT NULL,
 CONSTRAINT [PK_EST_NF_ENT_PRE_ENTRADA_PENDENCIA] PRIMARY KEY CLUSTERED 
(
	[CD_EMP] ASC,
	[CD_CTR_PRE_ENTRADA] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[EST_NF_ENT_PRE_ENTRADA_PENDENCIA] ADD  CONSTRAINT [DF_EST_NF_ENT_PRE_ENTRADA_PENDENCIA_CD_EMP]  DEFAULT ((0)) FOR [CD_EMP]

ALTER TABLE [dbo].[EST_NF_ENT_PRE_ENTRADA_PENDENCIA] ADD  CONSTRAINT [DF_EST_NF_ENT_PRE_ENTRADA_PENDENCIA_CD_CTR_PRE_ENTRADA]  DEFAULT ((0)) FOR [CD_CTR_PRE_ENTRADA]

ALTER TABLE [dbo].[EST_NF_ENT_PRE_ENTRADA_PENDENCIA] ADD  CONSTRAINT [DF_EST_NF_ENT_PRE_ENTRADA_PENDENCIA_DT_CAD]  DEFAULT (getdate()) FOR [DT_CAD]

ALTER TABLE [dbo].[EST_NF_ENT_PRE_ENTRADA_PENDENCIA]  WITH CHECK ADD  CONSTRAINT [FK_EST_NF_ENT_PRE_ENTRADA_PENDENCIA_EST_NF_ENT_PRE_ENTRADA] FOREIGN KEY([CD_EMP], [CD_CTR_PRE_ENTRADA])
REFERENCES [dbo].[EST_NF_ENT_PRE_ENTRADA] ([CD_EMP], [CD_CTR_PRE_ENTRADA])
ON DELETE CASCADE

ALTER TABLE [dbo].[EST_NF_ENT_PRE_ENTRADA_PENDENCIA] CHECK CONSTRAINT [FK_EST_NF_ENT_PRE_ENTRADA_PENDENCIA_EST_NF_ENT_PRE_ENTRADA]
end

INSERT INTO EST_NF_ENT_PRE_ENTRADA_PENDENCIA
SELECT
	EST_NF_ENT_PRE_ENTRADA.CD_EMP,
	EST_NF_ENT_PRE_ENTRADA.CD_CTR_PRE_ENTRADA,
	GETDATE()
FROM
	EST_NF_ENT_PRE_ENTRADA LEFT OUTER JOIN EST_NF_ENT_PRE_ENTRADA_EST_NF_ENT ON
	EST_NF_ENT_PRE_ENTRADA.CD_CTR_PRE_ENTRADA = EST_NF_ENT_PRE_ENTRADA_EST_NF_ENT.CD_CTR_PRE_ENTRADA
	LEFT OUTER JOIN EST_NF_ENT_PRE_ENTRADA_PENDENCIA ON
	EST_NF_ENT_PRE_ENTRADA.CD_CTR_PRE_ENTRADA = EST_NF_ENT_PRE_ENTRADA_PENDENCIA.CD_CTR_PRE_ENTRADA

WHERE
	EST_NF_ENT_PRE_ENTRADA_EST_NF_ENT.CD_CTR_PRE_ENTRADA IS NULL
	AND EST_NF_ENT_PRE_ENTRADA_PENDENCIA.CD_CTR_PRE_ENTRADA IS NULL
