PoshCode Archive  Artifact Content

Artifact 4039c9e115e95d4ab5f25e6a1cfde28cf715067e427547388af0469490a50b36:

  • File Script-Proc-sql.ps1 — part of check-in [9074d8ead2] at 2018-06-10 13:12:42 on branch trunk — A script that scripts a stored proc in SQL server. (user: Justin Dearing size: 2626)

# encoding: ascii
# api: powershell
# title: Script-Proc.sql
# description: A script that scripts a stored proc in SQL server.
# version: 0.1
# type: script
# author: Justin Dearing
# license: MITL
# x-poshcode-id: 2582
# x-archived: 2014-08-18T21:32:39
# x-published: 2011-03-26T12:16:00
#
#
#Copyright (c) 2011 Justin Dearing
#
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in
#all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
#THE SOFTWARE.

# The authoritative version is https://github.com/justaprogrammer/PowerShellScripts/blob/master/Script-Proc.ps1. 
# If you have a change I'd love to know about it to consider merging it into github.

param(
    [Parameter(Mandatory=$true,HelpMessage='The name of the stored procedure or user defined function we wish to script')]
    [string] $ProcedureName,
    [string] $Path = "$($ProcedureName).sql",
    [string] $ConnectionString = 'Data Source=.\sqlexpress2k8R2;Initial Catalog=master;Integrated Security=SSPI;'
);

try {
    [System.Data.SqlClient.SqlConnection] $cn = New-Object System.Data.SqlClient.SqlConnection (,$ConnectionString);
    $cn.Open() > $null;
    $cmd = $cn.CreateCommand();
    $cmd.CommandType = [System.Data.CommandType]::StoredProcedure;
    $cmd.CommandText = 'sp_helptext';
    $cmd.Parameters.AddWithValue('@objname', $ProcedureName) > $null;
    [System.Data.IDataReader] $rdr = $cmd.ExecuteReader();
    [string] $sproc_text = '';
    while ($rdr.Read()) {
        $sproc_text += $rdr[0];
    }
    $rdr.Close();
    $sproc_text | Out-File -FilePath $Path;
}
finally {
    if ($cmd -ne $null) { $cmd.Dispose(); }
    if ($cn -ne $null) { $cn.Dispose(); }
}