这是我使用的,改编自这里。
就我而言,我倾向于有很多目录,每个目录都有很多 SQL 文件,我想为每个目录创建一个单独的合并 SQL 文件。我只想合并以数字为前缀的文件(例如001_blah.sql
),而我的合并文件被命名为 upgrade_{DIRECTORY}.sql (例如merged_1370_to_1380.sql
)。
我将merge_sql_files.ps1
文件放在父目录中,并merge.bat
在每个目录中放置一个带有 SQL 文件的文件。
merge.bat
文件看起来像这样
@ECHO OFF
SET PsFile=merge_sql_files.ps1
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%..\%PsFile%
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'";
merge_sql_files.ps1
看起来像这样:
# Script to merge SQL files together.
# Takes all the SQL files that start with a number and concats
# them together, putting a line with "GO" in betweeen each one.
# The output is saved as upgrade_[DirectoryName].sql, e.g.
# 'upgrade_1370_to_1380.sql'.
#
# This script should be run from the folder with the sql files,
# e.g. put a merge.bat file in the folder that runs this ps1 script.
$path = (Resolve-Path .\).Path
$dirName = (get-item $path).Name
$outFile = "${path}\upgrade_${dirName}.sql"
if((Test-Path $outFile) -eq $true) {Remove-Item -Path $outFile -Force}
# Get all the SQL files that start with a number. Sort them
$files = Get-ChildItem -LiteralPath $path -Include "*.sql" | where {$_.Name -match "^[0-9]" } | Sort-Object -Property Name
New-Item -ItemType file -Path $outFile -Force | Out-Null
foreach($file in $files)
{
Write-Host "Appending file $file..." -ForegroundColor Gray
$content = Get-Content -Path $file.FullName
Add-Content -Path $outFile "----------------------------------------------------------------------------------------------------------------------------------------------------------------"
Add-Content -Path $outFile "-- $File"
Add-Content -Path $outFile "----------------------------------------------------------------------------------------------------------------------------------------------------------------"
Add-Content -Path $outFile $content
Add-Content -Path $outFile "GO`r`n"
}
Write-Host "Completed file $outFile" -ForegroundColor DarkGreen
# If running in the console, wait for input before closing.
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.FlushInputBuffer() # Make sure buffered input doesn't "press a key" and skip the ReadKey().
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}