IF OBJECT_ID('PDV_VD_NFCE_ARQ_DANFE') IS NULL
BEGIN
	RAISERROR('GERENCIAR LINK DE SINONIMO E UMA BOSTA. REMOVA ESTA LINHA E ALTERE O NOME DO BANCO ARQUIVOS',10,1)
	CREATE SYNONYM PDV_VD_NFCE_ARQ_DANFE FOR ALTERE_PARA_NOME_BANCO_ARQUIVOS..PDV_VD_NFCE_ARQ_DANFE 
END

GO

IF COL_LENGTH('PDV_VD_NFCE','CD_VD') IS NOT NULL
BEGIN
	EXECUTE SP_RENAME 'PDV_VD_NFCE','PDV_VD_NFCE_BKP_DATA'
END

GO

IF OBJECTPROPERTY(OBJECT_ID('PDV_VD_NFCE'),'isTable') = 0
BEGIN
	DROP SYNONYM PDV_VD_NFCE
END

GO

--DROP TABLE PDV_VD_NFCE
IF	OBJECT_ID('PDV_VD_NFCE') IS NULL
BEGIN

CREATE	TABLE PDV_VD_NFCE (
	CD_NFCE		BIGINT IDENTITY(1,1) PRIMARY KEY,
	CD_EMP		INT,
	CD_FILIAL	INT,
	DT_VD		DATETIME,
	CD_CX		INT,
	SERIE		INT,
	NR_NF		INT,
	TP_EMIS		INT,
	VER_APLIC	VARCHAR	(20),
	CH_NFE		VARCHAR (44),
	DT_RECBTO	DATETIME,
	NR_PROT		VARCHAR	(15),
	DIG_VAL		VARCHAR	(30),
	COD_STAT	VARCHAR	(3),
	DS_MOTIVO	VARCHAR	(255)
)

CREATE	INDEX		UK_PDV_VD_NFCE 
		ON			PDV_VD_NFCE (CD_EMP,CD_FILIAL,SERIE,NR_NF) 
		INCLUDE		(DT_VD,CD_CX,TP_EMIS,VER_APLIC,CH_NFE,DT_RECBTO,NR_PROT,DIG_VAL,COD_STAT,DS_MOTIVO) 

END

GO

IF OBJECTPROPERTY(OBJECT_ID('PDV_VD_NFCE_CANCEL'),'isTable') = 0
BEGIN
	DROP SYNONYM PDV_VD_NFCE_CANCEL
END

GO

--DROP TABLE PDV_VD_NFCE_CANCEL
IF	OBJECT_ID('PDV_VD_NFCE_CANCEL') IS NULL
BEGIN
CREATE	TABLE	PDV_VD_NFCE_CANCEL (
	CD_CANCEL	BIGINT IDENTITY(1,1) PRIMARY KEY,
	CD_NFCE		BIGINT NOT NULL FOREIGN KEY REFERENCES PDV_VD_NFCE(CD_NFCE),
	TP_EMIS		INT,
	VER_APLIC	VARCHAR	(20),
	CH_NFE		VARCHAR (44),
	DT_RECBTO	DATETIME,
	N_PROT		VARCHAR	(15),
	DIG_VAL		VARCHAR	(30),
	C_STAT		VARCHAR	(3),
	X_MOTIVO	VARCHAR	(255),
)

END

--DROP TABLE PDV_VD_PDV_VD_NFCE
IF	OBJECT_ID('PDV_VD_PDV_VD_NFCE') IS NULL
BEGIN
CREATE	TABLE	PDV_VD_PDV_VD_NFCE (
	CD_EMP		INT			NOT NULL,
	CD_FILIAL	INT			NOT NULL,
	CD_VD		INT			NOT NULL,
	CD_NFCE		BIGINT		NOT NULL
)	

ALTER	TABLE			PDV_VD_PDV_VD_NFCE 
		ADD CONSTRAINT	FK_PDV_VD_PDV_VD_NFCE_PDV_VD 
		FOREIGN KEY		(CD_VD, CD_FILIAL, CD_EMP)
		REFERENCES		PDV_VD (CD_VD, CD_FILIAL, CD_EMP)

ALTER	TABLE			PDV_VD_PDV_VD_NFCE
		ADD CONSTRAINT	FK_PDV_VD_PDV_VD_NFCE_PDV_VD_NFCE
		FOREIGN KEY		(CD_NFCE)
		REFERENCES		PDV_VD_NFCE (CD_NFCE)

END
		
/*
DROP SYNONYM PDV_VD_NFCE
EXECUTE SP_RENAME 'PDV_VD_NFCE_BKP_DATA','PDV_VD_NFCE'
*/
