Reputation: 61
Hi i am new to powershell and i have a scenario where i have a script to read all the CREATE TABLES from a sql file. Before these CREATE TABLES statement i have to print a IF EXIST statement which include the table name of the CREATE TABLE statement
Upvotes: 0
Views: 230
Reputation: 11188
Just uses a regex replace, something like this:
$x = Get-Content my_file.sql -raw
$r = @'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'$1')
DROP TABLE [dbo].[$1]
--GO
CREATE TABLE [dbo].[$1]
'@
$x -replace 'CREATE TABLE \[dbo\]\.\[([^\]]+)\]', $r
Upvotes: 1
Reputation: 4250
If $SqlStatements
is a variable holding the content then this works.
$ifExists = @'
IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'{0}')
DROP TABLE {1}
--GO
'@
[Regex]::Matches($SqlStatements, '\s*CREATE TABLE (\S+\.\[(\S+)\])') | Sort-Object Index -Descending | ForEach-Object {
$SqlStatements = $SqlStatements.Insert(
$_.Index,
"`r`n" + ($ifExists -f $_.Groups[2].Value, $_.Groups[1].Value) + "`r`n"
)
}
$SqlStatements
Replacements are done from the end tracking backwards. Attempting to go forwards will invalidate the Index value after the first insert.
Upvotes: 0