PowerShell - scripting - skip Encrypted\CLR Stored Procedures

Hi all,
Forgot where I got the code below from but, how would I skip Encrypted\CLR procedures because, I get error below...
Message
Executed as user: Loginname A job step received an error at line 81 in a PowerShell script. The corresponding line is '
$MyScripter.Script($proc)|out-null'. Correct the script and reschedule the job. The error information returned by PowerShell is: 'Exception calling "Script" with "1" argument(s): "The StoredProcedure '[dbo].[myrpocname]'
cannot be scripted as its data is not accessible."  '.  Process Exit Code -1.  The step failed.
#STORED PROCEDURES
if($procs -ne $null)
foreach ($proc in $procs)
#Assuming that all non-system stored procs have proper naming convention and don''t use prefixes like "sp_"
if ( $proc.Name.IndexOf("sp_") -eq -1 -and $proc.Name.IndexOf("xp_") -eq -1 -and $proc.Name.IndexOf("dt_") -eq -1)
$fileName = $proc.name
"Scripting SP $fileName"
$scriptfile = "$rootDrive\DatabaseScripts\$sqlDatabaseName\$strDate\StoredProcedures\$filename.sql"
New-Item $rootDrive\DatabaseScripts -type directory -force | out-null
New-Item $rootDrive\DatabaseScripts\$sqlDatabaseName -type directory -force | out-null
New-Item $rootDrive\DatabaseScripts\$sqlDatabaseName\$strDate -type directory -force | out-null
New-Item $rootDrive\DatabaseScripts\$sqlDatabaseName\$strDate\StoredProcedures -type directory -force | out-null
# SetScriptOptions
$MyScripter.Options.FileName = $scriptfile
#AppendTofile has to be ''true'' in order that all the procs'' scripts will be appended at the end
$MyScripter.Options.AppendToFile = "true"
$MyScripter.Script($proc)|out-null
Thanks
gv
Sword

You can exclude encrypted stored procedure using $_.IsEncrypted member.
$storedProcs = $db.StoredProcedures | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject -and  -not $_.IsEncrypted}
$server = "localhost"
$database = "PowerSQL"
$output_path = "F:\PowerSQL\"
$schema = "dbo"
$storedProcs_path = "$output_path\StoredProcedure\"
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server
$db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
$tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($server)
# Get the database and table objects
$db = $srv.Databases[$database]
$storedProcs = $db.StoredProcedures | Where-object { $_.schema -eq $schema -and -not $_.IsSystemObject -and -not $_.IsEncrypted}
# Set scripter options to ensure only data is scripted
$scripter.Options.ScriptSchema = $true;
$scripter.Options.ScriptData = $false;
#Exclude GOs after every line
$scripter.Options.NoCommandTerminator = $false;
$scripter.Options.ToFileOnly = $true
$scripter.Options.AllowSystemObjects = $false
$scripter.Options.Permissions = $true
$scripter.Options.DriAllConstraints = $true
$scripter.Options.SchemaQualify = $true
$scripter.Options.AnsiFile = $true
$scripter.Options.EnforceScriptingOptions = $true
function CopyObjectsToFiles($objects, $outDir) {
if (-not (Test-Path $outDir)) {
[System.IO.Directory]::CreateDirectory($outDir)
foreach ($o in $objects) {
if ($o -ne $null) {
$schemaPrefix = ""
if ($o.Schema -ne $null -and $o.Schema -ne "") {
$schemaPrefix = $o.Schema + "."
$scripter.Options.FileName = $outDir + $schemaPrefix + $o.Name + ".sql"
Write-Host "Writing " $scripter.Options.FileName -ErrorAction silentlycontinue
$scripter.EnumScript($o)
# Output the scripts
CopyObjectsToFiles $storedProcs $storedProcs_path
Write-Host "Finished at" (Get-Date)
-Prashanth

Similar Messages

  • Deserialization permissions error in CLR stored procedure

    Environment: SQL Server 2008 R2 standard edition and VS2010, .Net Framework 3.5
    I've got a table with a varbinary column that contains a serialized Hashtable. I'm writing a CLR stored procedure that, given the contents of such a field from a row in the table, does a lookup on a key in the Hashtable. and returns the element's value.
    To get the Hashtable, I need to deserialize it, and it appears that the BinaryFormatter's Deserialize function requires certain permissions that I don't know how to grant.
    This SQL Server instance runs on my own development machine, and was installed pretty much with all defaults. I'm the owner.
    Any help on solving this? I should point out while I write a fair amount of SQL and a LOT of VB, I'm far from a SQL Server expert, so if you have suggestions I'd appreciate it if you'd spell things out clearly for me.
    Thanks in advance for any help,
    Tom
    Here's a fragment from the VB source:
        ' the bytes variable is defined as Byte()
        Dim ms As MemoryStream = New MemoryStream()
        ms.Write(bytes, 0, bytes.Length)
        ms.Seek(0, 0)
        Dim formatter As New System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
        Dim oHT As Object = formatter.Deserialize(ms)    'hurls here
    The CREATE ASSEMBLY statement had WITH PERMISSION_SET = SAFE. I tried it with UNSAFE, and got this error:
    CREATE ASSEMBLY for assembly 'ddmi.deep.data.sqlserver' failed because assembly 'ddmi.deep.data.sqlserver' is not authorized for PERMISSION_SET = UNSAFE.  The assembly is authorized when either of the following is true: the database owner (DBO) has
    UNSAFE ASSEMBLY permission and the database has the TRUSTWORTHY database property on; or the assembly is signed with a certificate or an asymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission.
    Here's an SQL script that runs it:
    declare
        @id int
      , @raw_req_bin varbinary(1500)
      , @value nvarchar(max)
    set @id = 327
    set @raw_req_bin = (select raw_req_bin from dp_payment where transaction_id = @id)
    set @value = dbo.dp_fx_hash_table_lookup(@raw_req_bin, 'first_name')
    and here's what I get when I run the script:
    SecurityExceptionSystem.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
       at System.Security.CodeAccessSecurityEngine.SpecialDemand(PermissionType whatPermission, StackCrawlMark& stackMark)
       at System.Security.CodeAccessPermission.DemandInternal(PermissionType permissionType)
       at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
       at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
       at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
       at ddmi.deep.data.sqlserver.UserDefinedFunctions.AsHashTable(Byte[] bytes, String& phase)
    The action that failed was:
    Demand
    The type of the first permission that failed was:
    System.Security.Permissions.SecurityPermission
    The Zone of the assembly that failed was:
    MyComputer

    Set the database (in a test system) to trustworthy (ALTER DATABSE foo SET TRUSTWORTHY ON) for testing. If this works, look into code signing (sign an assembly and catalog the cert/asymmetric key to master) for production. If you have problems with
    "native" serialization, you might get better results using XML serializers.
    Re: XML serializers. SQLCLR will not load dynamically generated serializers. So you need to pregenerate XML serializers with sgen.exe.
    Your specific error message (the permission error) might be fixed by cataloging the SQLCLR assembly as UNSAFE. If that doesn't work, you might attempt to change the .NET permission configuration on your machine using either of the tools described here:
    http://msdn.microsoft.com/en-us/library/7c9c2y1w(v=vs.90).aspx
    Hope this helps, Cheers, Bob

  • Using C#  instead of pl/sql in a CLR stored procedure,  benefits?

    Hello dear experts,
    I was just playing around with C# and a little stored procedure I deployed to my Oracle 11.
    My questions are:
    Is it possible to call this "CLR c#" stored procedure in a different way than I call a standard pl/sql stored procedure from a C# client, maybe by something like referring to the same c# classname which I chose to wrap the stored procedure/function in?
    Is it possible to eg. return c# classes or c# arrays / own datatypes created within the CLR stored procedure to a C# client?
    Can I build up a c# array within my oracle c# stored procedure and return it to a C# client directly, or do I still have to do all the marshalling based on the standard pre-defined data types (number, varchar2 etc) myself and copy them to c# class members?
    Example: I have c# stored procedure like this:
    namespace oracle
    public class Crosssorter
    public static int GetChute(int parcelNo)
    int nChute=0;
    OracleConnection dbcon = new OracleConnection();
    dbcon.ConnectionString = "context connection=true"; // Wir benutzen die Session des Aufrufers
    dbcon.Open();
    OracleCommand cmd = dbcon.CreateCommand();
    cmd.CommandText = "select ChuteNo ...[blabla] ";
    cmd.Parameters.Add(":1", OracleDbType.Int32, parcelNo, ParameterDirection.Input);
    OracleDataReader reader = cmd.ExecuteReader();
    while (reader.Read())
    nChute = reader.GetInt32(0);
    reader.Close();
    cmd.Dispose();
    return (nChute);
    Can I reuse the class "Crosssorter" within my c# client application in order to access the function 'GetChute' more easily or is this classname only chosen because it has to have a name?
    Can I write an oracle C# stored proc so that a complex c# object is returned?
    So instead of a simple thing like 'public static int GetChute(int parcelNo)' maybe something like
    'public static int GetChute(
    int parcelNo,
    CChuteObject myChute)' <---- !!
    where CChuteObject is a C# class?
    In case all this is not possible, is there a solution to achieve this easily?
    Thank you for reading and thinking.
    Bernd.

    Hi Bernd,
    For best results, you may want to post this over in the [.NET Stored Procedures|http://forums.oracle.com/forums/forum.jspa?forumID=254] forum.
    Greg

  • Calling Managed CLR Stored Procedure from C++ SQL Server 2008 fails with Msg 2809

    I am trying to call a stored procedure from C++ (VS 2010).
    Here is what the stored procedure looks like:
    public class Validate
    [Microsoft.SqlServer.Server.SqlProcedure(Name = "ClientTest")]
    public static void ClientTest(out String res )
    { res = "50";}
    To create a stored procedure I deploy at first the assembly
    USE [test]
    GO
    CREATE ASSEMBLY ClientTestAssembly
    AUTHORIZATION testLogin
    FROM 'C:\Users\test\Documents\Visual Studio 2010\Projects\TestCreationAssemblyCSharp\TestCreationAssemblyCSharp\bin\x64\Debug\TestCreationAssemblyCSharp.dll'
    and call 
    USE test
    GO
    CREATE PROCEDURE ClientTest (@res NVARCHAR(40) OUTPUT)
    AS
    EXTERNAL NAME ClientTestAssembly.Validate.ClientTest
    I can call my procedure direct in SQL Server Management Studio without any errors
    declare @res nvarchar(10)
    execute ClientTest @res OUTPUT
    print @res
    But when I try to call this procedure from C++ using CALL syntax
    SQLBindParameter(sqlstatementhandle, 1, SQL_PARAM_OUTPUT, SQL_C_CHAR,
    SQL_VARCHAR , 40, 0, version, sizeof(version) ,
    &pcbValue);
    res = SQLExecDirect(sqlstatementhandle, (SQLCHAR*)("{CALL ClientTest(?) }"), SQL_NTS);
    I get the Error 2809 with SQLSTATE 42000 and with statement 
    The request for 'ClientTest'
    (procedure) failed because 'ClientTest' is a procedure object.
    However, if I wrap my CLR stored procedure into a T-SQL stored procedure, like
    CREATE PROCEDURE myProc (@res NVARCHAR(40) OUTPUT)
    AS
    EXEC ClientTest @res OUTPUT
    and call then myProc instead of ClientTest
    res = SQLExecDirect(sqlstatementhandle, (SQLCHAR*)("{CALL myProc(?) }"), SQL_NTS);
    everithing works fine and I get 50 as result.
    I have no ideas what is the reason for that behavior.
    Thanks very much for any suggestion. 
    Christina

    I'm not an ODBC expert, but you might try following the sample here:
    Process Return Codes and Output Parameters (ODBC)
    To see if it also behaves differently for your CLR proc.
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Transpose Data in CLR Stored procedure

    We have huge data table(600 columns and 800 rows approx) which we want to transpose 600 rows and 800 columns in a CLR stored procedure.
    Currently am using a datatable to the transpose. Could anyone suggest any better options other than datatable which gives better performance?

    Hi Hari,
    If my understand is correct, please consider using unpivot or pivot sql:
    http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
    http://blog.sqlauthority.com/2008/06/07/sql-server-pivot-and-unpivot-table-examples/
    Best Regards,
    Iric
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

  • SQL Server 2005 64-bit & SQL CLR Stored Procedures using DI API. COM Error.

    Hi,
    We've created a set of SQL CLR Stored Procs in C# .NET which use the DI API to import data into SAP (DEV was carried out on 32-bit environment).
    The DLLs and Interop.SAPbobsCOM have been successfully deployed as assemblies on SQL Server with their permission set to UNSAFE on the following environment:
    Microsoft Windows Server 2003 R2 Standard Edition 64-bit, Service Pack 2
    Microsoft SQL Server 2005 - 9.00.3073.00 (X64)
    SAP Business One 2007 A (8.00.180) SP:00 PL:45
    When executing the SQL CLR Stored Procs from SQL Server Management Studio, the following error is returned:
    "Retrieving the COM class factory for component with CLSID {632F4591-AA62-4219-8FB6-22BCF5F62007} failed due to the following error: 80040154."
    From our understanding, this occurs because SQL Server loads the assemblies into it's 64-bit process space, whereas the SAPbobsCOM is 32-bit. Are we assuming correctly?
    What can be done to solve this problem?

    Hi Jeremy,
    I'd agree with your assumption that it's to do with your DLL running in a 64 bit process. When you build your project, try setting the build properties to use a X86 instruction set (ie 32 bit).
    More details here:
    Re: Addon Develeped on 32bit Install on 64bit
    I've never tried for a CLR stored procedure but this is how you get around the issue when running a DI API addon on a 64 bit machine so hopefully it will work if the dll is executed by SQL Server. Let us know how you get on.
    Kind Regards,
    Owen

  • Invoke/Return Dataset from WebService in CLR Stored Procedure

    Hello,
    I am running SQL Server 2008 R2 or 2012 and Visual Studio 2010 Premium sp1. I have a stored procedure which currently returns a dataset which is used via SQLDataReader within a C# code-behind module in an ASP.NET application. This application uses the .NET
    4.0 framework. 
    I need to join the results from an external webservice (but within the same network) to this dataset. Instead of getting the data and putting it into a data table in code-behind (probably a HashTable which I could join with key/value pairs), I would like
    to get all of the data in the same stored procedure. I was thinking I could invoke the webservice and pass the input parms to the webservice then put the results into a temp table which I could then join with the query to the physical table.
    So, I have done quite a bit of researching online but have been unable to find any definitive answer or solution. I read the related forum thread "CLR Stored procedure consume webservice" but this does not address my versions of SQL Server / .NET
    framework.
    If someone could offer any suggestions or point in the right direction I would greatly appreciate it. Perhaps what I am trying to do is simply not possible?
    Regards,
    Buster

    Hello,
    I am trying to involve someone more familiar with this topic for a further look at this issue. Sometime delay might be expected from the job transferring. Your patience is greatly appreciated.
    Thank you for your understanding and support.
    Regards,
    Fanny Liu
    If you have any feedback on our support, please click here.
    Fanny Liu
    TechNet Community Support

  • Static variables in CLR stored procedures

    Is there really no way to use static variables shared by several CLS stored procedures in the same DLL, except by making them read only?
    Or can you add new server variables and read/write those from CLR stored procedures without having to open a connection and run a query each time you need a value?
    In my SP's, I would like to know the path where the database's .mdf file is stored on disk (not to access that file, but to store other files in a location that's always the same relative to the database).
    I thought I had found the solution last week, after some digging through sites like stackoverflow: make it a static read-only variable, and initialize it through a function call when the module is loaded.  The CLR will "forget" that it is
    read only at that time.
    For some reason this has worked perfectly for a week, but today it suddenly started failing -- without any code change or even a recompile, it started after a simple reboot of the test machine.
    The code (just the relevant lines, in VB syntax):
    Private Shared ReadOnly Datapath As String = InitDataPath()
    Private Shared Function InitDataPath() As String
    Try
    Using cn As New SqlConnection("context connection=true"),
    cmd As New SqlCommand("SELECT TOP 1 [physical_name] FROM sys.database_files WHERE type=0", cn)
    cn.Open()
    The "cn.open" line throws "Data access is not allowed in this context."
    It did not yet do that yesterday, and the day before, and all the way back to January 6th, when I wrote that piece of code.  The DLL hadn't even been recompiled since then, I was working on the application that uses the database and the stored procedures.

    I think I found it, at least it works again -- I just hope it's for more than a week now.
    Declare assembly as unsafe when installing it in SQL server (it was already 'EXTERNAL_ACCESS' for file I/O, but non-read-only static variables require UNSAFE).
    I initialize the static variables to 'Nothing' (NULL for C# users), and instead of finding the path when the module is loaded, I added a line 'if xxx is nothing then init()' at the start of each procedure / function. Init() is a a simple initialization
    routine that initializes the static variables upon first access.
    added SystemDataAccess:=DataAccessKind.Read to the declaration of UDF's (not possible and not necessary for procedures, apparently, but if what caused the assembly to load was a function, it would still fail).

  • Call a UNIX shell script from an oracle stored procedure

    We need to call a UNIX shell script from an oracle stored procedure
    i.e. the control should come back to the procedure once the script completes. Can any body help to achieve this ?

    There are various ways in achieving this.
    For Example, you can call a PRO*C-Library residing on the database server.
    This requires a PL/SQL library to be generated and some changes to the Listener configuration.
    It is also possible to implement a java procedure on the database being invoked by a PL/SQL wrapper class.
    In this way (and if used right) there is also granularity regarding the filestructure permissions given and it may be called during a Forms or other PL/SQL session.
    The article below explains a more generic approach how to invoke shell commands from within an Oracle Instance.
    Be careful with this, because it really works ;)
    Refer to :
    http://www.oracle-base.com/articles/8i/ShellCommandsFromPLSQL.php
    Message was edited by:
    user434854

  • Executing a shell script from pl/sql stored procedure

    Hi,
    I have Oracle 8i on HP-UX.
    I am passing a shell script name as a parameter to a user defined function from a pl/sql stored procedure. This user defined function has insterface to a user defined Java class file in Aurora java virtual machine which is written using runtime class which can execute any OS command or any shell script. I am getting any OS command run successfully, but could not run my own shell script. It's is not getting environment variables of my own, so not getting executed. So please suggest how can get these env variables in my shell script and also suggest other sucurity concerns to be taken into consideration.
    If you have any questions please let me know.
    This is really a very urgent issue.....
    Please help me.
    Thanks
    Srinivasa Rao Kolla

    Your best bet is to use the dbms_pipe builtin package to send the command to the host

  • Scripted JDBC and Oracle Stored Procedure with in/out Array

    The com.waveset.util.pooledconnection used by Scripted JDBC Adapter extends java.sql.connection.
    I need to pass an Varchar2 Array to the Stored Procedure. I tried using the oracle.sql.ARRAY and oracle.sql.ArrayDescriptor to pass the values, but get a casting exception,as the polledconnection implements only the java.sql.connection and not oracle.sql.connection.
    What are my options of using java.sql.Array with a PL/SQL procedure that takes a varchar2 array as in out parameter?
    Thanks
    Venki

    i ran my procedure which is very similar syndra posted
    create or replace procedure foo(p_dt in date, cv out sys_refcursor) as
    begin
    open cv for
    select e.*
    from table_xyz e
    where start_dt = p_dt;
    end;
    /Here is how is executed
    DECLARE
      P_DT DATE;
      CV SYS_REFCURSOR;
    BEGIN
      P_DT := '10-oct-2005';
      -- CV := NULL;  Modify the code to initialize this parameter
      scott.foo ( P_DT, CV );
      COMMIT;
    END;           
    -- i get PL/SQL procedure successfully complted , But i dont see the result set Or output
    - How do i see the output when i m using refcursor ?? i tried using print , but nothing didnt work
    - Any idea ??
    Thank you!!
    Edited by: user642297 on Jun 24, 2010 1:35 PM

  • Stored procedure with encryption?

    Hallo,
    Is there a opportunity, to encrypt a stored procedure in Oracle 9i like in MS SQL Server?
    Can I hide the content of a stored procedure, so not everbody is able to see the implementation?
    When yes, how?
    Best regards
    Stephan Schneider

    You can hide your source by Wrapping. It is a very old feature of Oracle (probably it was there in Oracle 7.3 or before also).
    http://download-west.oracle.com/docs/cd/A87860_01/doc/appdev.817/a77069/c_wrap.htm#1859

  • Need Example on calling a unix shell script from oracle stored procedure

    Hi
    Can anybody give example on how to call unix shell script from an Oracle stored procedure. Please give a small example on how to do this .I need this urgently please.
    Have a nice time.
    Thanks & Regards
    Jogesh

    If you are on 10g you can also use DBMS_SCHEDULER. See Re: Excute Unix command Using PL SQL

  • Change code in multiple stored procedures

    Hi,
        I have many stored procedures that have the server name hard-coded for bcp out purposes.  Is there a was to update all of these at one time, or am I stuck opening each one up seperately?
    Thanks
    Pam

    You can generate the ALTER scripts for all your stored procedures and then search-and-replace.
    David
    David http://blogs.msdn.com/b/dbrowne/

  • PowerShell SQL script to replace text in Triggers, Stored Procedure, can't get match

    I think my issue is with matching text and regular expression, any help would be appreciated.
    $server = "BOCADBD2";    
    # The SQL Server instance name
    $database = "SYSDB"; # The database name
    $matchText = "(raiserror\s@errno\s@errmsg)";
    # Definition text to search .Be aware this accepts a regular expression
    $replaceText =  "raiserror (@errmsg,16,1)";
    # Text to replace $matchText
    $alter = $false; # Set to true if you want the script to alter database objects
    $backupFolder = "v:\RaiseErrorTest\";
    # Change script folders. Need a \ (back slash) on the end
    $changeFolder = "v:\RaiseErrorTest\";
    # One file per object, backup & change folders
    $Hold = $matchText;
    # Load the SQL Management Objects assembly (Pipe out-null supresses output)
    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
    # Create our SMO objects
    $srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server;
    $db = New-Object ("Microsoft.SqlServer.Management.SMO.Database");
    # Get the database
    $db = $srv.Databases[$database];
    # For each stored procedure in the database
    foreach($proc in $db.StoredProcedures)
    # For each matching stored prcoedure
    if($proc.TextBody -match $matchText )
    Write-Host $matchText;
    Write-Host "Processing proc: " $proc.Name;
    # Backup of the original proc definition
    $proc.Script() | Out-File ($backupFolder + "procs\" + ([string]$srv.name -replace("\\", "_")) + "_" + [string]$db.Name + "_" + [string]$proc.name
    + "_backup.sql");
    # New procedure definition sql
    $proc.Script() -replace($matchtext, $replaceText) | Out-File ($changeFolder + "procs\" + ([string]$srv.name -replace("\\", "_")) + "_" + [string]$db.Name + "_"
    + [string]$proc.name + ".sql");
    # If set to true this will change the procedure definition on the server!
    if($alter)
    $proc.TextBody = $proc.TextBody -replace($matchtext, $replaceText);
    $proc.Alter();
    Write-Host "Altered " $proc.Name;

    I think $matchText is incorrect so I never get a match and was hopping for any suggestions.
    $replaceText  may be incorrect also, have looked for many hours on internet with no luck.
    How can we know if it is correct.  We cannot see the target text. Try it with an example of the test you are looking for.
    Your match only matches: "raiserror @errno @errmsg"
    And no other string.
    ¯\_(ツ)_/¯

Maybe you are looking for