<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>SQL Server &#8211; Furushima</title>
	<atom:link href="https://furushima.com.br/blog/category/sql-server/feed/" rel="self" type="application/rss+xml" />
	<link>https://furushima.com.br</link>
	<description>- Consultoria de Banco de Dados &#124; Furushima</description>
	<lastBuildDate>Sat, 27 Sep 2025 16:52:44 +0000</lastBuildDate>
	<language>pt-BR</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://furushima.com.br/wp-content/uploads/2024/02/cropped-favicon-32x32.png</url>
	<title>SQL Server &#8211; Furushima</title>
	<link>https://furushima.com.br</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>SQL Server &#8211; PowerShell para Exportação e Importação com BCP</title>
		<link>https://furushima.com.br/blog/sql-server-powershell-para-exportacao-e-importacao-com-bcp/</link>
		
		<dc:creator><![CDATA[Acacio Lima Rocha]]></dc:creator>
		<pubDate>Sat, 27 Sep 2025 16:52:44 +0000</pubDate>
				<category><![CDATA[Banco De Dados]]></category>
		<category><![CDATA[SQL Server]]></category>
		<guid isPermaLink="false">https://furushima.com.br/?p=2909</guid>

					<description><![CDATA[Salve, Salve rapaziada, bora de SQL Server hoje? 👀 Como todo bom DBAs, frequentemente nos deparamos com a necessidade de realizar operações de exportação e importação de dados entre bancos (Seja ele Oracle, SQL Server, MySQL etc). Essas tarefas, quando feitas manualmente, são propensas a erros e consomem um tempinho valioso. Pensando nisso, desenvolvi dois [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Salve, Salve rapaziada, bora de SQL Server hoje? 👀</p>



<p>Como todo bom DBAs, frequentemente nos deparamos com a necessidade de realizar operações de exportação e importação de dados entre bancos (Seja ele Oracle, SQL Server, MySQL etc). <br><br>Essas tarefas, quando feitas manualmente, são propensas a erros e consomem um tempinho valioso. Pensando nisso, desenvolvi dois scripts PowerShell que automatiza o processo usando o utilitário&nbsp;<strong>BCP</strong>&nbsp;(Bulk Copy Program).</p>



<p class="has-vivid-red-color has-text-color has-link-color wp-elements-97f38820eb6ad89bfb13592df938e187"><strong>⚠️ CONTÉM TEXTO MELHORADO POR AI – E TA TUDO BEM (SE SOUBER USAR 🤭)⚠️</strong></p>



<p>Coisa simples e rapida aqui:</p>



<h2 class="wp-block-heading">O Script de Exportação</h2>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: powershell; title: ; notranslate">
# Autor: Acaciolr-DBA - DBA BRABO
# Timestamp: 2025-09-25 15:49:06
# Descrição: Script PowerShell para realizar export com bcp.
#

# --- OPÇÕES DE NOMENCLATURA DISPONÍVEIS ---

&lt;#
EXEMPLOS DE NOMES GERADOS COM ESTE SCRIPT:

Formato atual (com data):
BFSQLPROD05_EGuardian_dbo_Usuarios_20250925.txt

Para usar outros formatos, substitua a linha do $FileName por uma das opções abaixo:

# Sem data (básico):
$FileName = &quot;$($ServerName)_$($DatabaseName)_$($SchemaName)_$($TableName).txt&quot;

# Com timestamp completo (data e hora):
$Timestamp = Get-Date -Format &quot;yyyyMMdd_HHmmss&quot;
$FileName = &quot;$($ServerName)_$($DatabaseName)_$($SchemaName)_$($TableName)_$Timestamp.txt&quot;

# Formato curto (sem servidor):
$FileName = &quot;$($DatabaseName)_$($SchemaName)_$($TableName)_$DateStamp.txt&quot;

# Apenas tabela com data:
$FileName = &quot;$($TableName)_$DateStamp.txt&quot;
#&gt;

# --- 1. CONFIGURAÇÕES INICIAIS ---

# Defina as variáveis de conexão e do export
$ServerName = &quot;SQLDBABRABO&quot;                     # Nome da instância do SQL Server
$DatabaseName = &quot;dbabraboDB&quot;                     # &lt;&lt; ATUALIZE ESTE VALOR &gt;&gt; Nome do banco de dados
$SchemaName = &quot;dbo&quot;                             # Nome do schema (geralmente &quot;dbo&quot;)
$TableName = &quot;TB_OCORRENCIAS_CLIENTE_OLD&quot;                       # &lt;&lt; ATUALIZE ESTE VALOR &gt;&gt; Nome da tabela a ser exportada
$OutputPath = &quot;C:\Temp\Export&quot;                  # Caminho para a pasta onde o arquivo será salvo
$Delimiter = &quot;|&quot;                                # Delimitador de campo (vírgula, ponto e vírgula, etc.)

# --- 2. GERAÇÃO AUTOMÁTICA DO NOME DO ARQUIVO ---

# Gera timestamp para incluir no nome do arquivo
$DateStamp = Get-Date -Format &quot;yyyyMMdd&quot;

# Gera o nome do arquivo automaticamente: servidor_database_schema_tabela_data.txt
$FileName = &quot;$($ServerName)_$($DatabaseName)_$($SchemaName)_$($TableName)_$DateStamp.txt&quot;

Write-Host &quot;Nome do arquivo gerado automaticamente: $FileName&quot; -ForegroundColor Cyan
Write-Host &quot;Padrão: &#x5B;SERVIDOR]_&#x5B;DATABASE]_&#x5B;SCHEMA]_&#x5B;TABELA]_&#x5B;DATA].txt&quot; -ForegroundColor Gray

# --- 3. VERIFICAÇÃO E PREPARAÇÃO ---

# Cria o caminho de saída se ele não existir
if (-not (Test-Path $OutputPath)) {
    Write-Host &quot;Caminho de saída '$OutputPath' não existe. Criando...&quot; -ForegroundColor Yellow
    New-Item -ItemType Directory -Path $OutputPath | Out-Null
}

$ExportFilePath = Join-Path -Path $OutputPath -ChildPath $FileName

# Exclui o arquivo anterior se ele existir
if (Test-Path $ExportFilePath) {
    Write-Host &quot;Arquivo existente '$ExportFilePath' será substituído.&quot; -ForegroundColor Yellow
    Remove-Item -Path $ExportFilePath -Force | Out-Null
}

# --- 4. EXECUÇÃO DO BCP ---

# A sintaxe do comando bcp:
# bcp &lt;database_name&gt;.&lt;schema_name&gt;.&lt;table_name&gt; out &lt;data_file&gt; -S &lt;server_name&gt; -T -t &lt;delimiter&gt; -c

# Parâmetros do BCP:
# out: indica que os dados serão exportados da tabela para um arquivo.
# -S: especifica o nome da instância do SQL Server.
# -T: usa a autenticação confiável (Windows Authentication). Para autenticação SQL, use -U e -P.
# -t: especifica o delimitador de campo.
# -c: usa modo de caractere. Se preferir modo nativo, use -n.

Write-Host &quot;Iniciando export da tabela '$TableName'...&quot; -ForegroundColor Green
Write-Host &quot;Arquivo de destino: $ExportFilePath&quot; -ForegroundColor Cyan

$bcpCommand = &quot;bcp &#x5B;$DatabaseName].&#x5B;$SchemaName].&#x5B;$TableName] out `&quot;$ExportFilePath`&quot; -S $ServerName -T -t`&quot;$Delimiter`&quot; -c&quot;

# Executa o comando bcp
Invoke-Expression $bcpCommand

# --- 5. VERIFICAÇÃO DO RESULTADO ---

# Verifica se o arquivo foi criado e tem conteúdo
if (Test-Path $ExportFilePath) {
    $fileSize = (Get-Item $ExportFilePath).Length
    
    if ($fileSize -gt 0) {
        Write-Host &quot;Export concluído com sucesso!&quot; -ForegroundColor Green
        Write-Host &quot;Arquivo salvo em: $ExportFilePath&quot; -ForegroundColor Cyan
        
        # Condicional - MB se for grande, KB se for pequeno
        if ($fileSize -gt 1MB) {
            Write-Host &quot;Tamanho do arquivo: $(&#x5B;math]::Round($fileSize / 1MB, 2)) MB&quot; -ForegroundColor Yellow
        } else {
            Write-Host &quot;Tamanho do arquivo: $(&#x5B;math]::Round($fileSize / 1KB, 2)) KB&quot; -ForegroundColor Yellow
        }
        
        # Informações adicionais sobre o arquivo gerado
        Write-Host &quot;Data do export: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')&quot; -ForegroundColor Gray
        
    } else {
        Write-Host &quot;O arquivo foi criado, mas está vazio. Verifique se a tabela tem dados ou se ocorreu algum erro na execução.&quot; -ForegroundColor Red
    }
} else {
    Write-Host &quot;ERRO: O arquivo '$ExportFilePath' não foi criado. Verifique as permissões de acesso ou o comando bcp.&quot; -ForegroundColor Red
}
</pre></div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img alt="" decoding="async" src="https://acaciolrdba.wordpress.com/wp-content/uploads/2025/09/image-1.png?w=850" alt="" class="wp-image-1622"/></figure></div>


<h2 class="wp-block-heading">Características Principais</h2>



<p>O script de exportação foi projetado para ser&nbsp;<strong>eficiente</strong>, incluindo:</p>



<ul class="wp-block-list">
<li><strong>Nomenclatura automática</strong>: Gera nomes de arquivos seguindo o padrão&nbsp;<code>Servidor_Database_Schema_Tabela_Data.txt</code></li>



<li><strong>Verificação de integridade</strong>: Confirma a criação do arquivo e valida seu tamanho</li>



<li><strong>Flexibilidade de delimitadores</strong>: Suporta qualquer caractere como separador (padrão: pipe&nbsp;<code>|</code>)</li>



<li><strong>Autenticação Windows</strong>: Usa credenciais integradas para segurança</li>
</ul>



<h3 class="wp-block-heading">Como Funciona</h3>



<p>O script automaticamente:</p>



<ol start="1" class="wp-block-list">
<li>Cria o diretório de destino se não existir</li>



<li>Remove arquivos anteriores com o mesmo nome</li>



<li>Executa o BCP com os parâmetros otimizados</li>



<li>Fornece um relatório detalhado do resultado</li>
</ol>



<h2 class="wp-block-heading">O Script de Importação</h2>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: powershell; title: ; notranslate">
# Autor: Acaciolr-DBA - DBA BRABO
# Timestamp: 2025-09-25 15:49:06
# Descrição: Script PowerShell para realizar import com bcp.
#

# --- 1. CONFIGURAÇÕES INICIAIS ---

# Defina as variáveis de conexão e do import
$ServerName = &quot;SQLDBABRABO&quot;                     # Nome da instância do SQL Server
$DatabaseName = &quot;dbabraboDB&quot;                     # &lt;&lt; ATUALIZE ESTE VALOR &gt;&gt; Nome do banco de dados
$SchemaName = &quot;dbo&quot;                                                             # Nome do schema (geralmente &quot;dbo&quot;)
$TableName = &quot;TB_OCORRENCIAS_CLIENTE_NEW&quot;                                       # &lt;&lt; ATUALIZE ESTE VALOR &gt;&gt; Nome da tabela de destino
$InputPath = &quot;C:\Temp\Export&quot;                                                   # Caminho para a pasta onde o arquivo está localizado
$FileName = &quot;BFSQLPROD05_EGuardian_dbo_TB_OCORRENCIAS_CLIENTE_20250925.txt&quot;     # Nome do arquivo de entrada (removido espaço no início)
$Delimiter = &quot;|&quot;                                                                # Delimitador de campo (vírgula, ponto e vírgula, etc.)
$ImportMode = &quot;REPLACE&quot;                                                          # APPEND (adicionar) ou REPLACE (substituir dados)

# Configurações adicionais
$FirstRow = 1                                                                   # Primeira linha a importar (2 se tem cabeçalho, 1 se não tem)
$BatchSize = 1000                                                               # Tamanho do lote para processamento
$ErrorFile = &quot;C:\Temp\Import_Errors.txt&quot;                                        # Arquivo para registrar erros

# --- 2. VERIFICAÇÃO E PREPARAÇÃO ---

$ImportFilePath = Join-Path -Path $InputPath -ChildPath $FileName

# Verifica se o arquivo de entrada existe
if (-not (Test-Path $ImportFilePath)) {
    Write-Host &quot;ERRO: O arquivo de entrada '$ImportFilePath' não foi encontrado!&quot; -ForegroundColor Red
    exit 1
}

# Verifica o tamanho do arquivo
$fileSize = (Get-Item $ImportFilePath).Length
Write-Host &quot;Arquivo de entrada encontrado: $ImportFilePath&quot; -ForegroundColor Green
Write-Host &quot;Tamanho do arquivo: $(&#x5B;math]::Round($fileSize / 1MB, 2)) MB&quot; -ForegroundColor Cyan

# Cria diretório para arquivo de erro se não existir
$ErrorDir = Split-Path $ErrorFile -Parent
if (-not (Test-Path $ErrorDir)) {
    New-Item -ItemType Directory -Path $ErrorDir -Force | Out-Null
}

# Remove arquivo de erro anterior
if (Test-Path $ErrorFile) {
    Remove-Item $ErrorFile -Force
}

# --- 3. PREPARAÇÃO DA TABELA (SE NECESSÁRIO) ---

if ($ImportMode -eq &quot;REPLACE&quot;) {
    Write-Host &quot;Modo REPLACE ativado. Truncando tabela de destino...&quot; -ForegroundColor Yellow
    
    $truncateCommand = @&quot;
sqlcmd -S $ServerName -d $DatabaseName -E -Q &quot;TRUNCATE TABLE &#x5B;$SchemaName].&#x5B;$TableName]&quot;
&quot;@
    
    try {
        Invoke-Expression $truncateCommand
        Write-Host &quot;Tabela truncada com sucesso.&quot; -ForegroundColor Green
    } catch {
        Write-Host &quot;ERRO ao truncar tabela: $($_.Exception.Message)&quot; -ForegroundColor Red
        exit 1
    }
}

# --- 4. VERIFICAÇÃO DA ESTRUTURA DA TABELA ---

Write-Host &quot;Verificando estrutura da tabela de destino...&quot; -ForegroundColor Cyan

$checkTableCommand = @&quot;
sqlcmd -S $ServerName -d $DatabaseName -E -Q &quot;SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$SchemaName' AND TABLE_NAME = '$TableName' ORDER BY ORDINAL_POSITION&quot; -h-1
&quot;@

try {
    $tableStructure = Invoke-Expression $checkTableCommand
    Write-Host &quot;Estrutura da tabela verificada.&quot; -ForegroundColor Green
    # Opcional: exibir estrutura
    # Write-Host $tableStructure
} catch {
    Write-Host &quot;AVISO: Não foi possível verificar a estrutura da tabela.&quot; -ForegroundColor Yellow
}

# --- BACKUP DA TABELA ORIGINAL COM DATA ---
Write-Host &quot;`n--- CRIANDO BACKUP DA TABELA ORIGINAL ---&quot; -ForegroundColor Yellow

# Extrai o nome original da tabela removendo &quot;_BKP&quot; do final (se existir)
if ($TableName -like &quot;*_BKP&quot;) {
    $OriginalTableName = $TableName -replace &quot;_BKP$&quot;, &quot;&quot;
} else {
    $OriginalTableName = $TableName
}

$BackupSuffix = &quot;_BKP_$(Get-Date -Format 'yyyyMMdd_HHmmss')&quot;  # Sufixo com data/hora
$BackupTableName = $OriginalTableName + $BackupSuffix

Write-Host &quot;Tabela original: $OriginalTableName&quot; -ForegroundColor Cyan
Write-Host &quot;Tabela de backup: $BackupTableName&quot; -ForegroundColor Cyan

# Comando SQL para criar a tabela de backup (apenas estrutura)
$backupCommand = @&quot;
sqlcmd -S $ServerName -d $DatabaseName -E -Q &quot;
SELECT * 
INTO &#x5B;$SchemaName].&#x5B;$BackupTableName] 
FROM &#x5B;$SchemaName].&#x5B;$OriginalTableName];
&quot;
&quot;@

try {
    Write-Host &quot;Criando estrutura da tabela de backup...&quot; -ForegroundColor Cyan
    Invoke-Expression $backupCommand
    Write-Host &quot;Tabela de backup criada com sucesso: $BackupTableName&quot; -ForegroundColor Green
} catch {
    Write-Host &quot;ERRO ao criar backup da tabela: $($_.Exception.Message)&quot; -ForegroundColor Red
    # Decide se quer continuar ou parar o script
    # exit 1  # Descomente se quiser parar o script em caso de erro
}

# --- VERIFICAÇÃO DO BACKUP ---
Write-Host &quot;Verificando a tabela de backup criada...&quot; -ForegroundColor Cyan

$verifyBackupCommand = @&quot;
sqlcmd -S $ServerName -d $DatabaseName -E -Q &quot;
SELECT 
    TABLE_NAME,
    TABLE_TYPE,
    TABLE_SCHEMA
FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME = '$BackupTableName'
AND TABLE_SCHEMA = '$SchemaName';
&quot; -h-1
&quot;@

try {
    $backupVerification = Invoke-Expression $verifyBackupCommand
    if ($backupVerification -match $BackupTableName) {
        Write-Host &quot;✓ Backup verificado com sucesso: $BackupTableName&quot; -ForegroundColor Green
    } else {
        Write-Host &quot;✗ A tabela de backup não foi encontrada.&quot; -ForegroundColor Red
    }
} catch {
    Write-Host &quot;Erro na verificação do backup: $($_.Exception.Message)&quot; -ForegroundColor Yellow
}

# --- 5. EXECUÇÃO DO BCP IMPORT ---

# A sintaxe do comando bcp para import:
# bcp &lt;database_name&gt;.&lt;schema_name&gt;.&lt;table_name&gt; in &lt;data_file&gt; -S &lt;server_name&gt; -E -t &lt;delimiter&gt; -c -F &lt;first_row&gt; -b &lt;batch_size&gt; -e &lt;error_file&gt;

# Parâmetros do BCP para import:
# in: indica que os dados serão importados do arquivo para a tabela.
# -S: especifica o nome da instância do SQL Server.
# -E: usa a autenticação confiável (Windows Authentication). Para autenticação SQL, use -U &lt;username&gt; -P &lt;password&gt;.
# -t: especifica o delimitador de campo.
# -c: usa modo de caractere.
# -F: especifica a primeira linha a ser importada (útil para pular cabeçalhos).
# -b: especifica o tamanho do lote.
# -e: especifica o arquivo para registrar erros.

Write-Host &quot;Iniciando import para a tabela '$TableName'...&quot; -ForegroundColor Yellow
Write-Host &quot;Primeira linha a importar: $FirstRow&quot; -ForegroundColor Cyan
Write-Host &quot;Tamanho do lote: $BatchSize&quot; -ForegroundColor Cyan

$bcpCommand = &quot;bcp &#x5B;$DatabaseName].&#x5B;$SchemaName].&#x5B;$TableName] in `&quot;$ImportFilePath`&quot; -S $ServerName -T -t`&quot;$Delimiter`&quot; -c -F$FirstRow -b$BatchSize -e`&quot;$ErrorFile`&quot;&quot; 

Write-Host &quot;Comando BCP: $bcpCommand&quot; -ForegroundColor Gray

# Executa o comando bcp e captura o resultado
try {
    $bcpResult = Invoke-Expression $bcpCommand 2&gt;&amp;1
    Write-Host $bcpResult -ForegroundColor White
} catch {
    Write-Host &quot;ERRO durante a execução do BCP: $($_.Exception.Message)&quot; -ForegroundColor Red
}

# --- 6. VERIFICAÇÃO DO RESULTADO ---

Write-Host &quot;`n--- VERIFICAÇÃO DOS RESULTADOS ---&quot; -ForegroundColor Yellow

# Verifica se houve erros
if (Test-Path $ErrorFile) {
    $errorContent = Get-Content $ErrorFile -ErrorAction SilentlyContinue
    if ($errorContent -and $errorContent.Length -gt 0) {
        Write-Host &quot;ATENÇÃO: Erros foram encontrados durante o import!&quot; -ForegroundColor Red
        Write-Host &quot;Arquivo de erros: $ErrorFile&quot; -ForegroundColor Red
        Write-Host &quot;Primeiras linhas dos erros:&quot; -ForegroundColor Red
        $errorContent | Select-Object -First 10 | ForEach-Object { Write-Host &quot;  $_&quot; -ForegroundColor Red }
    } else {
        Write-Host &quot;Nenhum erro registrado.&quot; -ForegroundColor Green
        # Remove arquivo de erro vazio
        Remove-Item $ErrorFile -Force -ErrorAction SilentlyContinue
    }
}

# Conta registros na tabela após o import
Write-Host &quot;Contando registros na tabela de destino...&quot; -ForegroundColor Cyan

$countCommand = @&quot;
sqlcmd -S $ServerName -d $DatabaseName -E -Q &quot;SELECT COUNT(*) as Total_Registros FROM &#x5B;$SchemaName].&#x5B;$TableName]&quot; -h-1
&quot;@

try {
    $recordCount = Invoke-Expression $countCommand
    $recordCount = ($recordCount -replace '\s+', '').Trim()
    Write-Host &quot;Total de registros na tabela: $recordCount&quot; -ForegroundColor Green
} catch {
    Write-Host &quot;Não foi possível contar os registros na tabela.&quot; -ForegroundColor Yellow
}

# Mostra algumas linhas de exemplo (opcional)
Write-Host &quot;`nPrimeiros registros importados:&quot; -ForegroundColor Cyan

$sampleCommand = @&quot;
sqlcmd -S $ServerName -d $DatabaseName -E -Q &quot;SELECT TOP 5 * FROM &#x5B;$SchemaName].&#x5B;$TableName]&quot; -h-1
&quot;@

try {
    $sampleData = Invoke-Expression $sampleCommand
    Write-Host $sampleData -ForegroundColor White
} catch {
    Write-Host &quot;Não foi possível exibir dados de exemplo.&quot; -ForegroundColor Yellow
}

# --- 7. RELATÓRIO FINAL ---

Write-Host &quot;`n=== RELATÓRIO FINAL DO IMPORT ===&quot; -ForegroundColor Green
Write-Host &quot;Servidor: $ServerName&quot; -ForegroundColor Cyan
Write-Host &quot;Banco: $DatabaseName&quot; -ForegroundColor Cyan
Write-Host &quot;Tabela: &#x5B;$SchemaName].&#x5B;$TableName]&quot; -ForegroundColor Cyan
Write-Host &quot;Arquivo importado: $ImportFilePath&quot; -ForegroundColor Cyan
Write-Host &quot;Tamanho do arquivo: $(&#x5B;math]::Round($fileSize / 1MB, 2)) MB&quot; -ForegroundColor Cyan
Write-Host &quot;Modo: $ImportMode&quot; -ForegroundColor Cyan
Write-Host &quot;Delimitador: '$Delimiter'&quot; -ForegroundColor Cyan
Write-Host &quot;Data/Hora: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')&quot; -ForegroundColor Cyan

if (Test-Path $ErrorFile) {
    Write-Host &quot;Arquivo de erros: $ErrorFile&quot; -ForegroundColor Red
} else {
    Write-Host &quot;Import concluído sem erros registrados!&quot; -ForegroundColor Green
}

Write-Host &quot;=== FIM DO RELATÓRIO ===&quot; -ForegroundColor Green

# --- 8. LIMPEZA (OPCIONAL) ---

# Descomente as linhas abaixo se quiser mover o arquivo processado para uma pasta de backup
# $BackupPath = &quot;C:\Temp\Import\Processados&quot;
# if (-not (Test-Path $BackupPath)) { New-Item -ItemType Directory -Path $BackupPath -Force | Out-Null }
# $BackupFile = Join-Path $BackupPath &quot;$(&#x5B;System.IO.Path]::GetFileNameWithoutExtension($FileName))_$(Get-Date -Format 'yyyyMMdd_HHmmss').txt&quot;
# Move-Item $ImportFilePath $BackupFile
# Write-Host &quot;Arquivo movido para: $BackupFile&quot; -ForegroundColor Yellow
</pre></div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img alt="" decoding="async" src="https://acaciolrdba.wordpress.com/wp-content/uploads/2025/09/image-2.png?w=1024" alt="" class="wp-image-1623"/></figure></div>

<div class="wp-block-image">
<figure class="aligncenter size-large"><img alt="" decoding="async" src="https://acaciolrdba.wordpress.com/wp-content/uploads/2025/09/image-3.png?w=1024" alt="" class="wp-image-1625"/></figure></div>


<h3 class="wp-block-heading">Destaques do Script de Importação</h3>



<p>A versão de importação vai além da simples carga de dados, incorporando&nbsp;<strong>mecanismos de segurança</strong>&nbsp;essenciais:</p>



<ul class="wp-block-list">
<li><strong>Sistema de backup automático</strong>: Cria uma cópia da tabela original antes do import</li>



<li><strong>Dois modos de operação</strong>:&nbsp;<code>APPEND</code>&nbsp;(adiciona dados) ou&nbsp;<code>REPLACE</code>&nbsp;(substitui tabela)</li>



<li><strong>Controle de erros robusto</strong>: Registra e reporta problemas detalhadamente</li>



<li><strong>Validação em múltiplos níveis</strong>: Verifica estrutura, conta registros e exibe amostras</li>
</ul>



<p><strong>Este é o coração da segurança do processo:</strong>&nbsp;antes de qualquer operação, é criado um backup datado da tabela original, permitindo recuperação instantânea em caso de problemas.</p>



<p>Bom rapaziada, fica ai uma dica que achei bacana e importante.</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
