PDC_REPORT_CreazioneDB/script/estrae_stored.ps1
2025-06-05 15:09:44 +02:00

58 lines
1.7 KiB
PowerShell

# Importa configurazione
. "$PSScriptRoot\conf.ps1"
# Imposta il percorso di output nella cartella sql
$OutputPath = Join-Path $env:workdir "sql\stored"
# Verifica che la directory di output esista, altrimenti la crea
if (-not (Test-Path -Path $OutputPath)) {
New-Item -ItemType Directory -Path $OutputPath | Out-Null
}
# Query per estrarre le stored procedures
$query = @"
SELECT
OBJECT_SCHEMA_NAME(object_id) as SchemaName,
OBJECT_NAME(object_id) as ProcedureName,
OBJECT_DEFINITION(object_id) as ProcedureDefinition
FROM sys.procedures
ORDER BY SchemaName, ProcedureName
"@
try {
# Importa il modulo SqlServer se non è già caricato
if (-not (Get-Module -Name SqlServer)) {
Import-Module SqlServer
}
# Esegui la query per ottenere le stored procedures
$storedProcedures = Invoke-Sqlcmd -ServerInstance $env:dbHost -Database $env:dbName -Query $query -Username $env:dbUser -Password $env:dbPassword
# Per ogni stored procedure trovata
foreach ($sp in $storedProcedures) {
$schemaName = $sp.SchemaName
$procName = $sp.ProcedureName
$definition = $sp.ProcedureDefinition
# Crea il nome del file
$fileName = Join-Path $OutputPath "${schemaName}_${procName}.sql"
# Scrivi il contenuto nel file
$content = @"
-- Schema: $schemaName
-- Stored Procedure: $procName
-- Data Estrazione: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
$definition
"@
$content | Out-File -FilePath $fileName -Encoding UTF8
Write-Host "Creato file per stored procedure: $schemaName.$procName"
}
Write-Host "`nEstrazione completata con successo!"
} catch {
Write-Error "Errore durante l'estrazione delle stored procedures: $_"
exit 1
}