Eggins.com
Powershell, .Net, Visual Studio, Team Foundation Server, Windows Communication Foundation

Powershell function to split SQL Server stored procedure script file

We do not yet have a good way to compare our Test and Production databases. This will be changing very soon. In the meantime, I have written the script below that may be of use for others without database compare tools.

You can script all of the stored procedures in a SQL Server 2005 database to a ".sql" file. The order of these stored procedures tends to be a little random, and therefore makes comparing two of these files impossible. The script below splits each stored procedure script into its own file so that you can use a directory compare tool to compare the files and see what changed.

It is not exactly the most readable powershell script, but it it works (for me). :-) 

Function Split-StoredProcedures ([string]$scriptedSpsFile) {
  ## This function takes a path to a file containing stored
  ## procedures, scripted from SQL Server 2005.
  ## It then splits all of the stored procedures into their
  ## own files. These files can then be compared to another
  ## set of scripted SP's using something
  ## like "Directory Toolkit" from "www.funduc.com"

  # Delete the output folder if it already exists,
  # and create the output folder
  [string]$OutputFolder = $scriptedSpsFile + ".Split"
  if (Test-Path $OutputFolder) {rd $OutputFolder -recurse}
  $null = md $OutputFolder

  # Get the content of the file at the path passed in by the user
  get-content -path $ScriptedSpsFile |
    %{
      # Locate the first line of a SP creation script
      if ($_.ToUpper() -eq "SET ANSI_NULLS ON" -and $FileName -ne $Null) {
        # Create the file for the previous SP
        $FileName += ".txt"
        $OutputFile = Join-Path -path $OutputFolder -childPath $FileName
        Set-Content -path $OutputFile -value $Cache
        $Cache = $Null
        $FileName = $Null
      }
      # Get the name of the SP, and put it in the FileName variable     
      if ($_.ToUpper() -like "CREATE PROCEDURE*") {
        $FileName =
          ([RegEx]::Matches($_, '\[dbo].\[(?<SpName>sp_.*)\]'))[0].Groups[1].Value
      }
      # Write the line to the cache for this SP
      $Cache += $_ + "`r`n"
     }
}

 


Posted Jun 01 2007, 03:34 PM by David
Filed under: , ,

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Copyright eggins.com, 1998 - 2008
Powered by Community Server (Non-Commercial Edition), by Telligent Systems