我正在尝试从数据库生成脚本,但稍微修改了这些对象。例如,我想为存储过程生成脚本,但我希望脚本在不同的模式下创建它。
我有一个我正在尝试下面的例子。如果我走向一个完全错误的方向,请指出我正确的方向。我想避免进行任何类型的字符串搜索和替换,因为它有很多潜在的危险。
我试图做的是从数据库中的现有函数创建一个函数对象,然后我创建一个新函数并尝试将它复制到我刚刚创建的那个函数中。这似乎有必要允许我更改模式,因为它必须在内存中而不是绑定到数据库。然后我尝试更改架构并编写脚本。不幸的是,我还没有找到.Script的语法,它不会因PowerShell中的错误而失败。
$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()
}
答案 0 :(得分:3)
当我输入我的问题时,我意识到.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()
}