我正在尝试使用Powershell从SQL Server读取视图和存储过程的定义。可以将定义作为create创建,并在具有相同名称的数据库上的新服务器中执行此操作。
有什么想法可以帮助我开始这个吗?我是Powershell的新手。
答案 0 :(得分:0)
这将帮助您入门。我不确定你需要做什么,但这将在PowerShell中运行一个存储过程。
我使用下面的文章来获取这些信息。 http://www.databasejournal.com/features/mssql/article.php/3683181/Microsoft-Windows-PowerShell-and-SQL-Server-2005-SMO-150-Part-II.htm
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]
你可能会做更多这样的事情,我不确定你是否使用PowerShell社区扩展,但是你去了(仅适用于2008年及以上):
1。)添加插件
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
2.)使用Invoke-SQLcmd
$query = "EXEC nameofsproc"
$db = "nameofdatabase"
$instance = "(local)"
$user = 'sa'
invoke-sqlcmd -query $query -database $db -serverinstance $instance -Variable
以下网站详细介绍了如何在Powershell中创建视图:
http://bi-bigdata.com/2013/03/10/powershell-tutorial-for-creating-view/
答案 1 :(得分:0)
假设对于创建视图,您已经拥有新服务器中的所有引用表
Import-Module SQLPS -DisableNameChecking
$serverName = 'your_source_InstanceName'
$dbname = 'your_source_DbName'
$destServerName = 'your_destination_InstanceName'
$destdbname = 'your_destination_DbName'
$destSrv = New-object "Microsoft.SqlServer.Management.SMO.Server" $destServerName
$destDb = $destSrv.Databases[$destdbname]
$srv = New-object "Microsoft.SqlServer.Management.SMO.Server" $serverName
$db = $srv.Databases[$dbname]
$scr = New-Object "Microsoft.SqlServer.Management.Smo.Scripter"
$scr.Server = $srv
$options = New-Object "Microsoft.SqlServer.Management.SMO.ScriptingOptions"
$options.AllowSystemObjects = $false
$options.SchemaQualify = $true
$options.ClusteredIndexes = $true
$options.Default = $true
$options.DriAll = $true
$options.Indexes = $true
$options.NonClusteredIndexes = $true
#Set options for SMO.Scripter
$scr.Options = $options
#StoredProcedures
$StoredProcedures = $db.StoredProcedures | where {$_.IsSystemObject -eq $false}
Foreach ($StoredProcedure in $StoredProcedures)
{
if ($StoredProcedures -ne $null)
{
Try{
$destDb.ExecuteWithResults($scr.Script($StoredProcedure))
}
Catch{
$err = $Error[0].Exception
Write-host "Error caught: " $err.Message;
While ($err.InnerException){
$err = $err.InnerException;
Write-Host "Inner exception:" $err.InnerException.Message;
};
return;
}
}
}
#Views
$views = $db.Views | Where {$_.IsSystemObject -eq $false}
Foreach ($view in $views)
{
if ($views -ne $null)
{
Try{
$destDb.ExecuteWithResults($scr.Script($View))
}
Catch{
$err = $Error[0].Exception
Write-host "Error caught: " $err.Message;
While ($err.InnerException){
$err = $err.InnerException;
Write-Host "Inner exception:" $err.InnerException.Message;
};
return;
}
}
}