INSERT statements containing regex as a string being read as regex

  • I am attempting to run a sql script with 4 simple INSERT statements. Each of the 4 INSERTS is inserting a regexp as an NVARCHAR string. 2 of them have within the string the combination of "$(" without quotes of course and 2 of them don't.

    I am holding the script contents in a variable and then executing nonquery, but I keep getting an error for the INSERTS containing the "$(". I know this is a sqlcmd replacement variable combination so i assume something similar is going on here in PoSH.

    Can anyone provide a better way to do this or provide a workaround?

    Snippet:

    FUNCTION runSql () {

    $dbName = "someDb"

    $tSql = "path\somesql.sql"

    [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SQLServer.SMO") | Out-Null

    $srv = NEW-OBJECT Microsoft.SqlServer.Management.Smo.Server("someServer")

    $db = New-Object Microsoft.SqlServer.Management.Smo.Database($srv, $dbName)

    $db.Create()

    $sr = New-Object System.IO.StreamReader($tSql)

    $script = $sr.ReadToEnd()

    $extype = [Microsoft.SQLServer.Management.Common.ExecutionTypes]::ContinueOnError

    $db.ExecuteNonQuery($script, $extype)

    }

    INSERTS causing issues:

    INSERT INTO [dbo].[regexes] ([regex])

    VALUES (N'%(NS)(.[^\^]{1,12}|\^)\^*(.[^\$]+)\$(.[^\^\$]+|\${1,35})\$*\w*\^(.[^\^]{1,29}|\^)\^*\?;636013(\d+)=\d+=\?#"\s(\w+\s\w+)\s+')

    INSERT INTO [dbo].[regexes] ([regex])

    VALUES (N'%(TX)(.[^\^]{1,12}|\^)\^*(.[^\$]+)\$(.[^\^\$]+|\${1,35})\$*\w*\^(.[^\^]{1,29}|\^)\^*\?;636015(\d+)=\d+\?#"\s(\d+)\s')

  • I am not able to recreate your issue using the ExecuteNonReader. One thing that looks odd is this line:

    $db.Create()

    Why are you trying to create a new database? Maybe this is from you boiling down the code for us. For me that part broke my demo, but either way I have a file in it with the two INSERTS you showed and they were inserted into a table perfectly using the other code you showed.

    There are no special teachers of virtue, because virtue is taught by the whole community.
    --Plato

  • ... and the first ID10T award of spring goes to... me.

    I had already resolved the problems I was having getting this to work via powershell; the real issue I had was when running a sql script via sqlcmd. Via sqlcmd, this combination of characters doesn't work so well.

    I have a process that creates database build scripts based on repos of database objects in source control (including data) and those scripts are used in processes that generate upgrade scripts. Occasionally I'll need to build another database from the repos manually and I take the created script but have to run it via sqlcmd because the size exceeds what can be used by SSMS.

    I'll cut the story off here and thank opc.three for making me realize how off track I was.

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply