|
| 1 | +[CmdletBinding()] |
| 2 | +Param ( |
| 3 | +# Accept Parameters |
| 4 | +[String[]]$SqlInstance = 'MSI', |
| 5 | +[String]$Database = 'DBA', |
| 6 | +[String]$FunctionName = "fn_classifier" |
| 7 | +) |
| 8 | + |
| 9 | +# Loop each SqlInstance |
| 10 | +foreach($srv in $SqlInstance) |
| 11 | +{ |
| 12 | + # Find Resource Governor Qualifier Function |
| 13 | + $QFName = (Invoke-DbaQuery -SqlInstance $SqlInstance -Database master -Query 'select OBJECT_NAME(classifier_function_id) as name from sys.dm_resource_governor_configuration').name; |
| 14 | + # Validate existence of QF |
| 15 | + if([String]::IsNullOrEmpty($QFName)){ |
| 16 | + Write-Warning "No Qualifier function found." |
| 17 | + Continue; |
| 18 | + } |
| 19 | + $FilePath = (Join-Path 'C:\Temp\' "$SqlInstance`__$FunctionName.sql") |
| 20 | + |
| 21 | + # Remove ScriptFile if existing |
| 22 | + if(Test-Path $FilePath) { Remove-Item $FilePath | Out-Null } |
| 23 | + $ScriptOut = Get-DbaDbUdf -SqlInstance $SqlInstance -Database master | Where-Object { $_.Name -eq $QFName } | Export-DbaScript -FilePath $FilePath -Passthru |
| 24 | + if(-not [String]::IsNullOrEmpty($Matches)){ $Matches.Clear() } |
| 25 | + |
| 26 | + # Build/Modify Function Definition |
| 27 | + @" |
| 28 | +USE [$Database] |
| 29 | +GO |
| 30 | +
|
| 31 | +"@ | Out-File -FilePath $FilePath -Force -Append |
| 32 | + foreach($line in $ScriptOut) |
| 33 | + { |
| 34 | + #$line = $line.Replace('WITH SCHEMABINDING',''); |
| 35 | + if($line -match ".*(?'Definition'CREATE.*FUNCTION.*\[dbo\]\.\[$QFName\]\(\s*\)).*") { |
| 36 | + $FunctionDefinition = $Matches['Definition'] |
| 37 | + $line = $line.Replace($FunctionDefinition,"ALTER FUNCTION [dbo].[$FunctionName] (@login_name nvarchar(256), @program_name nvarchar(256))"); |
| 38 | + $line = @" |
| 39 | +IF OBJECT_ID('dbo.$FunctionName') IS NULL |
| 40 | + EXEC ('CREATE FUNCTION $FunctionName() RETURNS INT AS BEGIN RETURN 1 END') |
| 41 | +GO |
| 42 | +
|
| 43 | +"@ + $line |
| 44 | + } |
| 45 | + $line = $line.Replace('APP_NAME()','@program_name') |
| 46 | + $line = $line.Replace('ORIGINAL_LOGIN()','@login_name') |
| 47 | + $line | Out-File -FilePath $FilePath -Force -Append |
| 48 | + } |
| 49 | + |
| 50 | + # Compile function |
| 51 | + Invoke-DbaQuery -SqlInstance $SqlInstance -Database $Database -File $FilePath |
| 52 | +} |
0 commit comments