Skip to content

Instantly share code, notes, and snippets.

@SQLvariant
Created July 29, 2020 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SQLvariant/7caf8faceca55d17d8df6b4911bb8d0a to your computer and use it in GitHub Desktop.
Save SQLvariant/7caf8faceca55d17d8df6b4911bb8d0a to your computer and use it in GitHub Desktop.
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