簡體   English   中英

使用powershell將一個sql文件拆分為多個文件

[英]Split a sql file into multiple files using powershell

嗨,我有一個包含多個(~400)這樣的插入語句的單個文件,我需要將其拆分為多個文件,每個文件中都有一個插入語句。 我猜它可以有效地使用 powershell 來完成。

PRINT N' Populating aud.DT'
GO
-- Insert into DT for Sanity
TRUNCATE TABLE aud.DT;
SET IDENTITY_INSERT aud.DT ON;
insert into aud.DT (Key,TableName,Description,SQL,Enabled,SingleRowTest) 
values (1,'dm.FCA','Desc1',
'select count(*) cnt 
from @SourceDB.dm.FCA  cp 
where cp.ProductionAmount > 0 and cp.ind = 0
AND cp.PMK BETWEEN CONVERT(VARCHAR(6), DATEADD(month, -2, GETUTCDATE()), 112)
AND    CONVERT(VARCHAR(6), GETUTCDATE(), 112)',1,0);

insert into aud.DT (Key,TableName,Description,SQL,Enabled,SingleRowTest) 
values (2,'dm.FCA','Desc2',
'select count(*) cnt
FROM @SourceDB.dm.FCA cp     
JOIN @SourceDB.dm.DimSubsidiary ds ON cp.key = ds.key 
WHERE (ds.SubsidiaryCode = ''NK'') 
and PMK  BETWEEN CONVERT(VARCHAR(6), DATEADD(month, -2, GETUTCDATE()), 112)
AND    CONVERT(VARCHAR(6), GETUTCDATE(), 112)',1,0);

insert into aud.DT (Key,TableName,Description,SQL,Enabled,SingleRowTest) 
values (3,' dm.FCR','Desc3',
from @SourceDB.dm.FCR  cp       
'select count(*) cnt 
inner join @SourceDB.ref.ask a on cp.key = a.key       
inner join @SourceDB.ref.clk c on cp.clk = c.clk       
where a.asi >= 300  and a.asi <= 399         
and c.cli > 200  and cp.pi = 0  
AND cp.PMK BETWEEN (CONVERT(VARCHAR(6), DATEADD(month, -2, GETUTCDATE()), 112))
        AND    CONVERT(VARCHAR(6), GETUTCDATE(), 112) ',1,0);

此外,文件名需要是 Test_[Key]_[Tablename.sql] 像 Test_0001_FCA.sql,Test_0010_FCR.sql 其中 [Key] 是插入到 aud.DT 表中的值

這應該有助於讓你朝着正確的方向前進:

$desktop = [Environment]::GetFolderPath("Desktop") #saving to desktop, adjust as needed
$file = Get-Content "C:\Temp\test.sql" #replace w/ your file location
$content = "" #variable to hold content for each individual file

$pre = "Test_"
$key = ""
$tableName = ""

foreach ($line in $file)
{

    if($line -eq "") #if line is blank, export file and reset everything
    {
      $outFile = $desktop + "\" + $pre + $key + "_" + $tableName + ".sql"
      $content | Out-File $outFile

      $key = ""
      $tableName = ""
      $content = ""
    }
    else 
    { #otherwise, collect line
        $content += $line + "`r`n"
        $words = $line -split " "

        if($words[0] -eq "insert") #if this is the insert, take the table name
        {
          $tableName = $words[2]
        }

        if($words[0] -eq "values") #if this is the values, take the key
        {
          $k = $words[1] -split ","
          $key = $k[0].Replace("(","").Replace(",","")
        }
    }


} # end loop
# get last chunk for final file
if($content -ne "")
{
    $outFile = $desktop + "\" + $pre + $key + "_" + $tableName + ".sql"
    $content | Out-File $outFile
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM