Microsoft SQL Server - Export / Dump d'une base
- 1. Introduction et choix du format
- 2. Prerequis (sqlcmd, droits, chemins)
- 3. Export .bak (BACKUP DATABASE)
- 4. Export .sql (mssql-scripter)
- 5. Export CSV / TSV (bcp)
- 6. Generate Scripts via SSMS (CLI silencieux)
- 7. dacpac / bacpac (SqlPackage)
- 8. Script PowerShell prêt a l'emploi
- 9. Automatisation (Tache planifiee Windows)
- 10. Depannage courant
1. Introduction et choix du format
Microsoft SQL Server propose plusieurs formats d'export selon l'usage cible :
| Format | Outil | Usage | Portable |
|---|---|---|---|
.bak | BACKUP DATABASE / sqlcmd | Backup binaire natif | MSSQL uniquement |
.sql | mssql-scripter | Script texte (schema + data) | Oui (versionnable, lisible) |
.csv / .tsv | bcp | Export d'une table | Oui (Excel, MySQL, etc.) |
.bacpac | SqlPackage | Schema + data compresse (Azure-friendly) | MSSQL / Azure SQL |
.dacpac | SqlPackage | Schema uniquement | MSSQL / Azure SQL |
- Restauration sur un autre MSSQL ? .bak
- Migration vers MySQL / PostgreSQL ? .sql ou CSV (voir doc Conversion)
- Suivi en Git / diff ? .sql
- Migration vers Azure SQL ? .bacpac
2. Prerequis
2.1 Outils en ligne de commande
# Verifier que sqlcmd est installe
sqlcmd -?
# Verifier que bcp est installe
bcp -v
# Si absent : installer les "Microsoft Command Line Utilities for SQL Server"
# https://learn.microsoft.com/sql/tools/sqlcmd-utility
# ou via le pack "ODBC Driver" + "MSSQL Tools"
2.2 Lister les bases disponibles
# Authentification Windows (-E)
sqlcmd -S localhost -E -Q "SELECT name FROM sys.databases ORDER BY name"
# Avec instance nommee
sqlcmd -S localhost\SQLEXPRESS -E -Q "SELECT name FROM sys.databases"
# Authentification SQL Server
sqlcmd -S localhost -U sa -P MotDePasse -Q "SELECT name FROM sys.databases"
# Recuperer le nom du serveur / version
sqlcmd -S localhost -E -Q "SELECT @@SERVERNAME, @@VERSION"
2.3 Droits requis
BACKUP DATABASE: roledb_backupoperatorousysadminmssql-scripter:db_datareader+ permissions sur les objets systeme (VIEW DEFINITION)bcp out:SELECTsur la table source
.bak. Verifier dans services.msc → SQL Server (MSSQLSERVER) → Connexion.
3. Export .bak (BACKUP DATABASE)
3.1 Backup complet (FULL)
# Authentification Windows
sqlcmd -S localhost -E -Q "BACKUP DATABASE [MaBase] TO DISK='D:\backup\MaBase_FULL.bak' WITH FORMAT, INIT, COMPRESSION, STATS=10"
# Authentification SQL
sqlcmd -S localhost -U sa -P MotDePasse -Q "BACKUP DATABASE [MaBase] TO DISK='D:\backup\MaBase_FULL.bak' WITH FORMAT, INIT, COMPRESSION"
Options principales
| Option | Effet |
|---|---|
FORMAT | Reinitialise completement le fichier (ecrase l'en-tete media) |
INIT | Ecrase les jeux de sauvegarde existants dans le fichier |
NOINIT | Ajoute le backup au fichier existant (par defaut) |
COMPRESSION | Compresse le .bak (~ 50-70% de gain). Necessite Standard/Enterprise |
NO_COMPRESSION | Desactive la compression (par defaut sur Express) |
STATS=10 | Affiche la progression tous les 10% |
CHECKSUM | Verifie l'integrite a l'ecriture |
3.2 Backup avec date dans le nom
# PowerShell : insere la date dans le nom de fichier
$date = Get-Date -Format "yyyy-MM-dd_HHmm"
$base = "MaBase"
$dest = "D:\backup\${base}_${date}.bak"
sqlcmd -S localhost -E -Q "BACKUP DATABASE [$base] TO DISK='$dest' WITH FORMAT, INIT, COMPRESSION, STATS=10"
3.3 Backup differentiel
sqlcmd -S localhost -E -Q "BACKUP DATABASE [MaBase] TO DISK='D:\backup\MaBase_DIFF.bak' WITH DIFFERENTIAL, INIT, COMPRESSION"
3.4 Backup du journal des transactions
# Necessite recovery model FULL ou BULK_LOGGED
sqlcmd -S localhost -E -Q "BACKUP LOG [MaBase] TO DISK='D:\backup\MaBase_LOG.trn' WITH INIT, COMPRESSION"
3.5 Verifier l'integrite du .bak apres export
sqlcmd -S localhost -E -Q "RESTORE VERIFYONLY FROM DISK='D:\backup\MaBase_FULL.bak'"
# Lister le contenu du fichier (jeux de sauvegarde)
sqlcmd -S localhost -E -Q "RESTORE HEADERONLY FROM DISK='D:\backup\MaBase_FULL.bak'"
# Lister les fichiers logiques (MDF/LDF) contenus
sqlcmd -S localhost -E -Q "RESTORE FILELISTONLY FROM DISK='D:\backup\MaBase_FULL.bak'"
3.6 Backup vers plusieurs fichiers (parallelisation)
# Repartition sur 4 fichiers : plus rapide sur disques rapides
sqlcmd -S localhost -E -Q "BACKUP DATABASE [MaBase]
TO DISK='D:\backup\MaBase_1.bak',
DISK='D:\backup\MaBase_2.bak',
DISK='D:\backup\MaBase_3.bak',
DISK='D:\backup\MaBase_4.bak'
WITH FORMAT, INIT, COMPRESSION, STATS=10"
4. Export .sql (mssql-scripter)
mssql-scripter est l'equivalent officiel de mysqldump pour MSSQL : il produit un fichier .sql en texte clair (schema, donnees, ou les deux).
4.1 Installation
# Necessite Python 3.x
pip install mssql-scripter
# Verifier
mssql-scripter --help
4.2 Export complet (schema + donnees)
# Authentification Windows
mssql-scripter -S localhost -d MaBase --integrated-auth --schema-and-data -f D:\backup\MaBase.sql
# Authentification SQL
mssql-scripter -S localhost -d MaBase -U sa -P MotDePasse --schema-and-data -f D:\backup\MaBase.sql
4.3 Schema uniquement (DDL)
mssql-scripter -S localhost -d MaBase --integrated-auth --schema-only -f D:\backup\MaBase_schema.sql
4.4 Donnees uniquement (INSERT)
mssql-scripter -S localhost -d MaBase --integrated-auth --data-only -f D:\backup\MaBase_data.sql
4.5 Options utiles
| Option | Effet |
|---|---|
--include-objects table1 table2 | Exporter uniquement certaines tables |
--exclude-objects schema.tableX | Exclure certains objets |
--exclude-use-database | Omet le USE [base] au debut |
--target-server-version 2019 | Genere du SQL compatible MSSQL 2019 |
--script-create | Genere des CREATE (defaut) |
--script-drop-create | Genere DROP puis CREATE |
--check-for-existence | Ajoute IF EXISTS avant DROP |
4.6 Export d'une table specifique avec donnees
mssql-scripter -S localhost -d MaBase --integrated-auth `
--schema-and-data `
--include-objects dbo.Clients dbo.Commandes `
-f D:\backup\extrait.sql
.sql est beaucoup plus lent qu'un .bak (parfois x10 a x50 sur les grosses bases). Reserver aux bases < 5 Go ou aux exports partiels.
5. Export CSV / TSV (bcp)
bcp (Bulk Copy Program) est l'utilitaire ultra-rapide pour exporter/importer des tables au format texte ou binaire.
5.1 Export d'une table en CSV
# Auth Windows (-T)
bcp MaBase.dbo.Clients out "D:\backup\clients.csv" -c -t"," -r"\n" -S localhost -T
# Auth SQL (-U / -P)
bcp MaBase.dbo.Clients out "D:\backup\clients.csv" -c -t"," -S localhost -U sa -P MotDePasse
5.2 Options bcp principales
| Option | Effet |
|---|---|
-c | Format caracteres (texte UTF-8/ANSI) |
-w | Format caracteres Unicode (UTF-16 LE) |
-n | Format binaire natif (rapide, MSSQL uniquement) |
-t"," | Separateur de champ (defaut : \t) |
-r"\n" | Separateur de ligne (defaut : \r\n) |
-T | Authentification Windows |
-U / -P | Auth SQL Server |
-S serveur | Serveur cible |
-q | Identificateurs entre crochets (utile si table = mot reserve) |
-C 65001 | Code page UTF-8 (eviter les pb d'accents) |
5.3 Export via requete (queryout)
# Exporter le resultat d'une requete (pas une table entiere)
bcp "SELECT Id, Nom, Email FROM MaBase.dbo.Clients WHERE Actif=1" queryout "D:\backup\clients_actifs.csv" -c -t"," -S localhost -T
5.4 Export de toutes les tables (boucle PowerShell)
$server = "localhost"
$base = "MaBase"
$dest = "D:\backup\csv"
New-Item -ItemType Directory -Force -Path $dest | Out-Null
$tables = & sqlcmd -S $server -d $base -E -h-1 -W -Q "SET NOCOUNT ON; SELECT s.name + '.' + t.name FROM sys.tables t JOIN sys.schemas s ON t.schema_id = s.schema_id"
foreach ($t in $tables) {
$t = $t.Trim()
if ($t -and $t -notlike "*rows affected*") {
$out = Join-Path $dest "$($t -replace '\.','_').csv"
& bcp "$base.$t" out $out -c -t"," -S $server -T
}
}
-C 65001 pour eviter les caracteres mal encodes lors d'un import dans MySQL/PostgreSQL :
bcp MaBase.dbo.Clients out clients.csv -c -t"," -C 65001 -S localhost -T
6. Generate Scripts via SSMS (en ligne de commande)
SSMS (SQL Server Management Studio) propose un assistant graphique Tasks → Generate Scripts qui peut etre lance via la DLL Microsoft.SqlServer.Management.SmoExtended en PowerShell.
6.1 Export schema + data via SMO (PowerShell)
Import-Module SqlServer
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server "localhost"
$db = $srv.Databases["MaBase"]
$scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter $srv
$scripter.Options.ScriptSchema = $true
$scripter.Options.ScriptData = $true
$scripter.Options.ScriptDrops = $false
$scripter.Options.WithDependencies = $true
$scripter.Options.IncludeHeaders = $true
$scripter.Options.FileName = "D:\backup\MaBase_SMO.sql"
$scripter.Options.ToFileOnly = $true
$scripter.Options.Encoding = [System.Text.Encoding]::UTF8
# Lister toutes les tables
$tables = $db.Tables | Where-Object { -not $_.IsSystemObject }
$scripter.EnumScript($tables) | Out-Null
7. dacpac / bacpac (SqlPackage)
SqlPackage.exe est l'outil Microsoft pour exporter/importer des bases au format .bacpac (schema + data) ou .dacpac (schema seul). Format de choix pour Azure SQL et les migrations entre versions de SQL Server.
7.1 Installation
# SqlPackage est inclus dans :
# - SQL Server Data Tools (SSDT)
# - Azure Data Studio
# - Telechargement standalone : https://learn.microsoft.com/sql/tools/sqlpackage/sqlpackage-download
# Verifier
SqlPackage /?
7.2 Export .bacpac (schema + data)
SqlPackage /Action:Export `
/SourceServerName:"localhost" `
/SourceDatabaseName:"MaBase" `
/TargetFile:"D:\backup\MaBase.bacpac" `
/SourceTrustServerCertificate:True
7.3 Extract .dacpac (schema seul)
SqlPackage /Action:Extract `
/SourceServerName:"localhost" `
/SourceDatabaseName:"MaBase" `
/TargetFile:"D:\backup\MaBase.dacpac"
8. Script PowerShell pret a l'emploi
Script complet, parametrable, avec rotation des sauvegardes (conserve les N derniers backups).
<#
.SYNOPSIS
Export MSSQL .bak avec compression et rotation
.EXAMPLE
.\backup-mssql.ps1 -Server "localhost" -Database "MaBase" -Destination "D:\backup" -Retention 7
#>
param(
[string]$Server = "localhost",
[string]$Database = "MaBase",
[string]$Destination = "D:\backup",
[int] $Retention = 7,
[string]$User = $null,
[string]$Password = $null
)
# Creer le dossier si besoin
if (-not (Test-Path $Destination)) {
New-Item -ItemType Directory -Force -Path $Destination | Out-Null
}
# Nom du fichier
$date = Get-Date -Format "yyyy-MM-dd_HHmm"
$file = Join-Path $Destination "${Database}_${date}.bak"
# Construire la commande sqlcmd
$query = "BACKUP DATABASE [$Database] TO DISK='$file' WITH FORMAT, INIT, COMPRESSION, CHECKSUM, STATS=10"
if ($User -and $Password) {
$args = @("-S", $Server, "-U", $User, "-P", $Password, "-Q", $query)
} else {
$args = @("-S", $Server, "-E", "-Q", $query)
}
Write-Host "[$(Get-Date -Format 'HH:mm:ss')] Backup de $Database vers $file..." -ForegroundColor Cyan
& sqlcmd $args
if ($LASTEXITCODE -eq 0) {
$size = [math]::Round((Get-Item $file).Length / 1MB, 2)
Write-Host "[OK] Backup termine ($size Mo)" -ForegroundColor Green
# Rotation : supprimer les fichiers trop anciens
Get-ChildItem $Destination -Filter "${Database}_*.bak" |
Sort-Object LastWriteTime -Descending |
Select-Object -Skip $Retention |
ForEach-Object {
Write-Host " Suppression : $($_.Name)" -ForegroundColor Yellow
Remove-Item $_.FullName -Force
}
} else {
Write-Host "[ERREUR] Backup en echec (code $LASTEXITCODE)" -ForegroundColor Red
exit 1
}
9. Automatisation (Tache planifiee Windows)
9.1 Creer la tache via PowerShell
$action = New-ScheduledTaskAction -Execute "powershell.exe" `
-Argument "-NoProfile -ExecutionPolicy Bypass -File C:\scripts\backup-mssql.ps1 -Database MaBase -Destination D:\backup -Retention 7"
$trigger = New-ScheduledTaskTrigger -Daily -At 02:00
$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -TaskName "MSSQL_Backup_MaBase" `
-Action $action -Trigger $trigger -Principal $principal `
-Description "Backup quotidien MSSQL"
9.2 Tester immediatement
Start-ScheduledTask -TaskName "MSSQL_Backup_MaBase"
Get-ScheduledTaskInfo -TaskName "MSSQL_Backup_MaBase"
9.3 Alternative : SQL Server Agent (Standard / Enterprise)
USE msdb;
EXEC sp_add_job @job_name = N'Backup_MaBase';
EXEC sp_add_jobstep
@job_name = N'Backup_MaBase',
@step_name = N'Backup full',
@subsystem = N'TSQL',
@command = N'BACKUP DATABASE [MaBase] TO DISK=''D:\backup\MaBase.bak'' WITH INIT, COMPRESSION';
EXEC sp_add_schedule
@schedule_name = N'Quotidien_02h',
@freq_type = 4, @freq_interval = 1,
@active_start_time = 020000;
EXEC sp_attach_schedule @job_name = N'Backup_MaBase', @schedule_name = N'Quotidien_02h';
EXEC sp_add_jobserver @job_name = N'Backup_MaBase';
10. Depannage courant
| Erreur | Cause | Solution |
|---|---|---|
Cannot open backup device. Operating system error 5 (Access is denied) |
Le compte de service SQL Server n'a pas les droits NTFS sur le dossier | Ajouter MSSQLSERVER ou NT Service\MSSQLSERVER en ecriture sur le dossier |
Operating system error 3 (The system cannot find the path) |
Dossier inexistant cote serveur | Creer le dossier sur le serveur (le chemin est evalue cote SQL Server, pas cote client) |
BACKUP DATABASE permission denied |
Utilisateur sans role db_backupoperator |
EXEC sp_addrolemember 'db_backupoperator', 'utilisateur' |
The transaction log for database is full |
Mode recovery FULL sans backup LOG | Faire un BACKUP LOG ou passer en SIMPLE |
sqlcmd : command not found |
SqlCmd Tools non installe | Installer Microsoft Command Line Utilities for SQL Server |
SSL Provider: certificate chain was issued by an authority that is not trusted (sqlcmd 18+) |
Connexion chiffree au certificat auto-signe | Ajouter -C (TrustServerCertificate) : sqlcmd -S localhost -E -C -Q "..." |
mssql-scripter : ModuleNotFoundError |
Python 3.12+ : distutils retire |
Utiliser Python 3.11, ou installer setuptools avant : pip install setuptools |
.bak et MSSQL - Conversion vers MySQL / PostgreSQL pour les migrations entre SGBD.