80 lines
2.6 KiB
PowerShell
80 lines
2.6 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
|
||
}
|
||
|
||
try {
|
||
# Importa il modulo SqlServer se non è già caricato
|
||
if (-not (Get-Module -Name SqlServer)) {
|
||
Import-Module SqlServer
|
||
}
|
||
|
||
# Query per estrarre la stored procedure
|
||
$query = @"
|
||
SELECT
|
||
s.name as SchemaName,
|
||
o.name as ProcedureName,
|
||
CAST(m.definition as NVARCHAR(MAX)) as ProcedureDefinition
|
||
FROM sys.sql_modules m
|
||
INNER JOIN sys.objects o ON m.object_id = o.object_id
|
||
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
|
||
WHERE o.type = 'P'
|
||
-- AND o.name = 'CercaCaratteriAnomali_20150205'
|
||
"@
|
||
|
||
# Esegui la query
|
||
$storedProcedures = Invoke-Sqlcmd -ServerInstance $env:dbHostInput -Database $env:dbName -Query $query -Username $env:dbUser -Password $env:dbPassword -MaxCharLength 1000000
|
||
|
||
# Funzione per pulire il nome del file
|
||
function Clean-FileName {
|
||
param([string]$name)
|
||
# Sostituisce caratteri non validi con underscore
|
||
$invalidChars = [IO.Path]::GetInvalidFileNameChars()
|
||
$invalidChars += '[', ']', ' ', '(', ')', '{', '}', '´', '`', '''', '"'
|
||
$result = $name
|
||
foreach ($char in $invalidChars) {
|
||
$result = $result.Replace($char, '_')
|
||
}
|
||
return $result
|
||
}
|
||
|
||
# Per ogni stored procedure trovata
|
||
foreach ($sp in $storedProcedures) {
|
||
$schemaName = Clean-FileName $sp.SchemaName
|
||
$procName = Clean-FileName $sp.ProcedureName
|
||
$definition = $sp.ProcedureDefinition
|
||
|
||
# Crea il nome del file
|
||
$fileName = Join-Path $OutputPath "${schemaName}_${procName}.sql"
|
||
|
||
# Formatta il contenuto
|
||
# -- Schema: $schemaName
|
||
# -- Stored Procedure: $procName
|
||
|
||
$content = @"
|
||
$($definition.Trim())
|
||
"@
|
||
|
||
# Rimuovi righe vuote multiple
|
||
$lines = $content -split "`r`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
|
||
$content = $lines -join "`r`n"
|
||
|
||
# Scrivi il contenuto nel file con codifica UTF8 con BOM
|
||
$utf8WithBom = New-Object System.Text.UTF8Encoding($true)
|
||
[System.IO.File]::WriteAllText($fileName, $content, $utf8WithBom)
|
||
|
||
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
|
||
}
|