DECLARE @dbName NVARCHAR(128);
DECLARE @sql NVARCHAR(MAX);

SELECT TOP 1 @dbName = name
FROM sys.databases
WHERE name LIKE '%NFe%';

IF @dbName IS NOT NULL
BEGIN
    SET @sql = N'
    IF NOT EXISTS (
    SELECT 1 
    FROM ' + QUOTENAME(@dbName) + N'.sys.objects 
    WHERE name = ''EST_NFE_INFEFETPGTOINTEG'' 
      AND type = N''U''
	)
	BEGIN
		CREATE TABLE ' + QUOTENAME(@dbName) + N'.dbo.EST_NFE_INFEFETPGTOINTEG (
			ID BIGINT IDENTITY(1,1) PRIMARY KEY,
			CHAVE_NFE VARCHAR(60) COLLATE SQL_Latin1_General_CP1_CI_AS,
			NRO INT,
			CD_LOTE INT,
			CNPJ VARCHAR(14)COLLATE SQL_Latin1_General_CP1_CI_AS,
			CD_NF INT,
			NF_NF INT,
			TP_MOV INT,
			DT DATETIME,
			HT DATETIME,
			ST INT,
			DS_MOTIVO VARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
			DS_RETORNO VARCHAR(1) COLLATE SQL_Latin1_General_CP1_CI_AS,
			VERSAO VARCHAR(10) COLLATE SQL_Latin1_General_CP1_CI_AS,
			APLICATIVO VARCHAR(50) COLLATE SQL_Latin1_General_CP1_CI_AS,
			NR_PROTOCOLO VARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
			DATA_PROTOCOLO DATETIME,
			DS_PROTOCOLO VARCHAR(100) COLLATE SQL_Latin1_General_CP1_CI_AS,
			ARQ_XML VARBINARY(MAX)
		);
	END';

    EXEC sp_executesql @sql;
END
ELSE
BEGIN
    PRINT 'Nenhum banco de dados de NFe foi encontrado.';
END;

