未加星标

List and Execute SQL Server Stored Procedures with PowerShell

字体大小 | |
[系统(windows) 所属分类 系统(windows) | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

By:Adam Bertram || Related Tips:More >Stored Procedures

Problem

A common task many Database Administrators (DBA) perform on a regular basis is working with SQL Server stored procedures . Stored procedures allow the DBA to automate a certain task by bundling up a query and executing as a single set of logic. This is considerable progress in including more automation, but why not automate the automation? To create a stored procedure a DBA might go into SQL Server Management Studio (SSMS), click through the GUI and create a stored procedure that way or, likewise, when executing a stored procedure pursue the same path. This is a waste of your precious time! Let's automate that.

Solution

What I mean by "automating the automation" is building a tool in PowerShell that allows us to retrievestored procedures for review and execute them all from the command line. Among many other benefits, this gives us the advantage of then being able to add these commands to larger automation projects down the road. Let's see how we can build this tool and show how it works.

First of all, we'll need to download and install a few prerequisites if you don't already have SSMS installed. To speed things up below is some PowerShell code that downloads and installs each of the required packages to make our tool work. This code will download each MSI package in your user temp directory and run the install on each.

$files = [ordered]@{
'SQLSysClrTypes.msi' =
'http://go.microsoft.com/fwlink/?LinkID=239644&clcid=0x409'
'SharedManagementObjects.msi' =
'http://go.microsoft.com/fwlink/?LinkID=239659&clcid=0x409'
'PowerShellTools.msi' =
'http://go.microsoft.com/fwlink/?LinkID=239656&clcid=0x409'
}
foreach ($file in $files.GetEnumerator())
{
$downloadFile
= (Join-Path -Path $env:TEMP -ChildPath $file.Key)
if (-not
(Test-Path -Path $downloadFile -PathType Leaf))
{
Invoke-WebRequest -Uri $file.Value -OutFile $downloadFile
}
Start-Process
-FilePath 'msiexec.exe' -Args "/i $downloadFile /qn" -Wait
}

Now that you've got the prerequisites downloaded, we can begin designing our tool.

To build a great PowerShell tool, it's important to make the code inside as generic as possible while creating input parameters in a way that encourages reuse. This means bringing out items that might change over time and building in as parameter rather than a static reference. In this instance, this will be things like the SQL Server instance name, database name, stored procedure name and so on. Let's first start off with a function to run a stored procedure. This function (as well as all the following functions we'll be building) all have the appropriate parameters.

function Invoke-SqlStoredProcedure
{
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ServerName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$Database,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$Name,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[pscredential]$Credential
)
begin
{
$ErrorActionPreference = 'Stop'
}
process
{
try
{
$connectionString = New-SqlConnectionString -ServerName $ServerName -Database $Database -Credential $Credential
$SqlConnection = New-SqlConnection -ConnectionString $connectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandType=[System.Data.CommandType]StoredProcedure
$SqlCmd.CommandText = $Name
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
}
catch
{
$PSCmdlet.ThrowTerminatingError($_)
}
}
}

Most of this code is available with SMO when you install the SQLPS module. However, notice the references to New-SqlConnectionString and New-SqlConnection. Those are custom functions I've chosen to break out. Why? Because we're not only going to build this function but also one to retrieve a list of all stored procedures that exist on a server. With these standard commands broken out into other commands, they can be shared. I won't bore you with the details on them but if you're interested, feel free to take a look at the module I've created on Github .

Now notice the other function that I've created to list all of the stored procedures on a SQL server.

function Get-SqlStoredProcedure
{
[OutputType([Microsoft.SqlServer.Management.Smo.StoredProcedure])]
[CmdletBinding()]
param
(
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$ServerName,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]$Database,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[pscredential]$Credential
)
begin
{
$ErrorActionPreference = 'Stop'
}
process
{
try
{
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$connectionString = New-SqlConnectionString -ServerName $ServerName -Database $Database -Credential $Credential
$sqlConnection = New-SqlConnection -ConnectionString $connectionString
$serverInstance = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $sqlConnection
$serverInstance.Databases[$Database].StoredProcedures
}
catch
{
$PSCmdlet.ThrowTerminatingError($_)
}
}
}

Notice here I can also refer to these shared functions since making that initial connection is a common attribute both share. This is a best practice when building a tool like this. It's important to first mentally think of what you're going to accomplish before you start. In our case, it was invoking a stored procedure and listing them on a server. Then, as you begin to build your tool notice code they might have in common and break those out into other functions.

For the final test, let's take our tool for a test run. I have a SQL database in Azure to try this out on. First, I'll try to query all of the stored procedures in my myazuredatabase database on that server.

Get-SqlStoredProcedure -ServerName adbsql.database.windows.net -Database myazuredatabase Credential (Get-Credential)

After supplying my SQL username and password you should see something like this:


List and Execute SQL Server Stored Procedures with PowerShell

This begins to enumerate each stored procedure and display each stored procedure's properties.

I know that I have a stored procedure called uspLogError in this database. Let's run Invoke-SqlStoredProcedure and see if that works as well.

Invoke-SqlStoredProcedure -ServerName adbsql.database.windows.net -Database myazuredatabase -Name dbo.uspLogError -Credential (Get-Credential)
List and Execute SQL Server Stored Procedures with PowerShell

Great! After providing my username and password again, you can see that it returns whatever the stored procedure is designed to. In this case, it was merely 0.

You can see that building a tool in PowerShell can save you a ton of time. By using this at the console to make ad-hoc queries or incorporating it into a bigger orchestration process, you'll save tons of time to get back to doing more important things.

Next Steps Check out the following res

本文系统(windows)相关术语:三级网络技术 计算机三级网络技术 网络技术基础 计算机网络技术

主题: SQLPowerShellSQL ServerGit
分页:12
转载请注明
本文标题:List and Execute SQL Server Stored Procedures with PowerShell
本站链接:http://www.codesec.net/view/481324.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 系统(windows) | 评论(0) | 阅读(27)