Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Split .SQL files with ScriptDOM
<#################################################################################################
Pre-reqs: Install the SqlServer module.
#################################################################################################>
Import-Module -Name SqlServer
Add-Type -LiteralPath "C:\Program Files (x86)\Microsoft SQL Server\140\DAC\bin\Microsoft.SqlServer.TransactSql.ScriptDom.dll"
[Microsoft.SqlServer.TransactSql.ScriptDom.TSql140Parser] $parser = new-object Microsoft.SqlServer.TransactSql.ScriptDom.TSql140Parser($false)
<#################################################################################################
Qucik Helper-function to turn the file into a script fragment, using scriptdom.
#################################################################################################>
function Get-ScriptComments($ScriptPath){
$Reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $ScriptPath
$Errors = $null
$ScriptFrag = $parser.Parse($Reader, [ref]$Errors)
# Look for Drop Statements
($ScriptFrag.ScriptTokenStream).where({$_.TokenType -eq 'MultilineComment'})
}
<#################################################################################################>
$ScriptPath = ".\AdventureWorksAddress.sql"
$s = Get-Content -Raw ( Resolve-Path $ScriptPath )
$ScriptFrags = Get-ScriptComments -ScriptPath $ScriptPath
$StartCode=0
foreach($Frag in $ScriptFrags | WHERE { $_.Column -lt 6 } ) {
$Comment=[pscustomobject]@{
Offset = $Frag.Offset;
TextLength = $Frag.Text.Length;
Column = $Frag.Column;
Text = $Frag.Text
}
$CodeLength = $Comment.Offset-$StartCode
if($StartCode -gt $CodeLength){$CodeLength = ($s.Length-$StartCode)-1}
$s.Substring($StartCode, $CodeLength)
$s.Substring($Comment.Offset, $Comment.TextLength)
$StartCode = $Comment.Offset + $Comment.TextLength
}
var visitor = new MyVisitor();
visitor.Visit(sqlFragment);
public class MyVisitor : TSqlConcreteFragmentVisitor
{
public override void ExplicitVisit(CreateProcedureStatement node)
{
base.ExplicitVisit(node);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.