Created
July 29, 2020 18:53
-
-
Save SQLvariant/7caf8faceca55d17d8df6b4911bb8d0a to your computer and use it in GitHub Desktop.
Split .SQL files with ScriptDOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<################################################################################################# | |
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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