IF NOT EXISTS (
    SELECT 1
    FROM sys.tables
    WHERE name = 'est_nf_nfe_recebimento_bkp_FARMAGOI_66446'
)
and EXISTS (
    SELECT 1
    FROM sys.views
    WHERE name = 'V_EST_NF_NFE_RECEBIMENTO_PENDENTE_FILA'
)

BEGIN
		CREATE TABLE [dbo].[est_nf_nfe_recebimento_bkp_FARMAGOI_66446](
			[ID] [bigint] NOT NULL,
			[CD_FILIAL] [int] NULL,
			[CHAVE_NFE] [varchar](100) NULL,
			[IDE_NATOP] [varchar](100) NULL,
			[IDE_SERIE] [int] NULL,
			[IDE_NNF] [int] NULL,
			[IDE_DEMI] [datetime] NULL,
			[EMIT_CNPJ] [varchar](14) NULL,
			[EMIT_XNOME] [varchar](150) NULL,
			[EMIT_XMUN] [varchar](50) NULL,
			[DEST_CNPJ] [varchar](14) NULL,
			[DEST_XNOME] [varchar](150) NULL,
			[DEST_XMUN] [varchar](100) NULL,
			[TOTAL_VNF] [money] NULL,
			[PROT_NPROT] [varchar](50) NULL,
			[PROT_DIGVAL] [varchar](50) NULL,
			[PROT_XMOTIVO] [varchar](100) NULL,
			[DH_IMPORT] [datetime] NOT NULL,
			[ARQ_NFE] [varbinary](max) NULL,
			[MD5] [varchar](50) NULL,
			[LAUDO] [varbinary](max) NULL,
			[STS_IMPORT] [int] NOT NULL,
			[FILENAME] [varchar](500) NULL);

			WITH XMLNAMESPACES (DEFAULT 'http://www.portalfiscal.inf.br/nfe')
			INSERT INTO est_nf_nfe_recebimento_bkp_FARMAGOI_66446
			SELECT R.*
			FROM est_nf_nfe_recebimento r
			INNER JOIN V_EST_NF_NFE_RECEBIMENTO_PENDENTE_FILA vw
				ON r.id = vw.id
			WHERE EXISTS (
				SELECT 1
				FROM EST_NF_ENT_DANFE_PROVISORIO pro
				WHERE pro.NR_AUTORIZADOR =
					TRY_CAST(CONVERT(VARCHAR(MAX), vw.arq_nfe) AS XML)
					.value('(/nfeProc/protNFe/infProt/chNFe)[1]', 'varchar(100)')
			)
			and r.CHAVE_NFE is null;



			WITH XMLNAMESPACES (DEFAULT 'http://www.portalfiscal.inf.br/nfe')
			DELETE r
			FROM est_nf_nfe_recebimento r
			INNER JOIN V_EST_NF_NFE_RECEBIMENTO_PENDENTE_FILA vw
				ON r.id = vw.id
			WHERE EXISTS (
				SELECT 1
				FROM EST_NF_ENT_DANFE_PROVISORIO pro
				WHERE pro.NR_AUTORIZADOR =
					TRY_CAST(CONVERT(VARCHAR(MAX), vw.arq_nfe) AS XML)
					.value('(/nfeProc/protNFe/infProt/chNFe)[1]', 'varchar(100)')
			)
			and r.CHAVE_NFE is null
END




