Click here to Skip to main content
15,889,371 members
Articles / Programming Languages / SQL
Technical Blog

Powershell Scripts to Replace Key Value Pair in SQL Script File Before Running the SQL Scripts

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
18 Aug 2015CPOL 7K   1   1
Powershell Scripts to replace Key Value pair in SQL Script file before running the SQL Scripts

Consider having the following SQL file:

C:\PowershellTest\UpdateImagesLocation.sql

SQL
DECLARE @ImagesLocation NVARCHAR(max)
SET @ImagesLocation = 'C:\ImagesStore\' 
.....

Now, when you run this SQL scripts file during the deployments, you would also want to change the value of @ImagesLocation, as the location may vary for different environment.

This can be achieved through using regular expressions in Powershell scripts.

In order to do that, you can create the following function in your Powershell deployment or pre-deployment scripts:

#if an SQL file contains 'SET @variable_name=value', then this function can be called to replace value by actual value.

JavaScript
function replacePatternMatchingValueInFile( $file, $key, $value ) {
    $content = Get-Content $file
    if ( $content -match "^$key\s*=" ) {
        $content -replace "^$key\s*=.*", "$key = $value" |
        Set-Content $file     
    } else {
        Add-Content $file "$key = $value"
    }
}

Call this function in the following manner:

$scriptfile = "C:\PowershellTest\UpdateImagesLocation.sql"
replacePatternMatchingValueInFile $scriptfile"SET @ImagesLocation" "'\\datashare\appImages'"

As a result, the variable assignment for @ImagesLocation would be changed to a different value in the SQL file.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGreate Pin
Aladár Horváth19-Aug-15 2:51
professionalAladár Horváth19-Aug-15 2:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.