我正在尝试从数据库生成脚本,但对这些对象稍作修改。例如,我想为存储过程生成脚本,但我希望脚本在不同的架构下创建它。
我有一个我目前正在尝试的例子。如果我正朝着一个完全错误的方向前进,那么请指出我正确的方向。我想避免进行任何类型的字符串搜索和替换,因为这有很多潜在的危险。
我试图做的是从数据库中的现有函数创建一个函数对象,然后我创建一个新函数并尝试使其成为我刚刚创建的函数的副本。这似乎有必要让我更改架构,因为它必须在内存中并且不绑定(bind)到数据库。然后我尝试更改架构并编写脚本。不幸的是,我无法找到不会因 PowerShell 中的错误而失败的 .Script 语法。
$instance = $args[0] # Gets the instance name from the command line parameters
$database = $args[1] # Gets the database name from the command line parameters
# Import the SMO assembly
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
# Create an instance for the SQL Server
$serverInstance = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $instance
# Create an instance for the Database
$databaseInstance = $serverInstance.Databases[$database]
# Loop through all of the user defined functions (that are not system objects) in the database
foreach ($function in $databaseInstance.UserDefinedFunctions | Where-Object {$_.IsSystemObject -eq $False})
{
$newFunction = New-Object ('Microsoft.SqlServer.Management.Smo.UserDefinedFunction') ($databaseInstance, $function.Name, "tnf_dbo_func")
$newFunction.TextHeader = $function.TextHeader
$newFunction.TextBody = $function.TextBody
$newFunction.TextMode = $False
$newFunction.ChangeSchema("tnf_dbo_func")
$newFunction.TextMode = $True
Write-Host $newFunction.Schema
Write-Host $newFunction.TextHeader
Write-Host $newFunction.TextBody
$newFunction.Script()
}
最佳答案
当我输入我的问题时,我意识到 .TextMode 设置来自我正在尝试的另一个解决方案。删除那些解决了问题。由于问题已经输入,我想我还是会发布它,以防万一这对其他人有帮助。
更正后的代码:
$instance = $args[0] # Gets the instance name from the command line parameters
$database = $args[1] # Gets the database name from the command line parameters
# Import the SMO assembly
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
# Create an instance for the SQL Server
$serverInstance = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $instance
# Create an instance for the Database
$databaseInstance = $serverInstance.Databases[$database]
# Loop through all of the user defined functions (that are not system objects) in the database
foreach ($function in $databaseInstance.UserDefinedFunctions | Where-Object {$_.IsSystemObject -eq $False})
{
$newFunction = New-Object ('Microsoft.SqlServer.Management.Smo.UserDefinedFunction') ($databaseInstance, $function.Name, "tnf_dbo_func")
$newFunction.TextHeader = $function.TextHeader
$newFunction.TextBody = $function.TextBody
$newFunction.ChangeSchema("tnf_dbo_func")
Write-Host $newFunction.Schema
Write-Host $newFunction.TextHeader
Write-Host $newFunction.TextBody
$newFunction.Script()
}
关于sql-server - 如何在 PowerShell 中使用 SMO 编写稍微改变的对象的脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2821120/