2016-12-20 3 views
0

.sqlファイルに複数のストアドプロシージャと関数スクリプトが含まれています。PowerShell 2.0 1つのSQLファイルを実行する(複数のSPと関数を持つ)

Invokeコマンドを使用したくないのは、私のサーバーがそれらをサポートしていないためです。

現在、.sqlファイルにストアドプロシージャまたはストアドプロシージャが1つしかない場合、正常に動作する以下のコードを使用しています。

$scriptDetail = Get-Content $sqlScriptLocation \t | Out-String 
 
$scriptDetail = $scriptDetail -creplace 'GO','' 
 
$scriptDetail = $scriptDetail -replace 'SET ANSI_NULLS ON','' 
 
$scriptDetail = $scriptDetail -replace 'SET QUOTED_IDENTIFIER ON','' 
 
$ConnectionString = “Server=$dataSource;uid=$user; pwd=$cred;Database=$database;” 
 
$sqlCon = New-Object -TypeName System.Data.SqlClient.SqlConnection -ArgumentList $ConnectionString 
 
$sqlCon.Open() 
 
$sqlCmd = New-Object -TypeName System.Data.SqlClient.SqlCommand 
 
$sqlCmd.Connection = $sqlCon 
 
$sqlCmd.CommandText = $scriptDetail 
 
$sqlCmd.ExecuteNonQuery() \t \t 
 
$sqlCon.Close()

彼らは

System.Data.SqlClient.SqlException(0x80131904)のようなエラーcasusedので、私は上記のコードでGOや他の2つのコマンドを置き換えています:付近に正しくない構文」をGO '

System.Data.SqlClient.SqlException(0x80131904):' CREATE FUNCTION 'はクエリの最初のステートメントでなければなりませんバッチ

私はいくつかの掘削後の溶液を思い付いているスカラー変数「@variablename」

+0

$ sqlScriptLocation = "C:\ All_Restore_PROCEDUREFunctiond.sql" – TahirAyoub

答えて

0

を宣言する必要があり、完全なファイルを読み込んで配列に入れ、その後、foreachループを実行し、それが得られますforeachループ内の各行は、条件を置けばその コードが

$SQLConnection = New-Object System.Data.SqlClient.SqlConnection 
 
$SQLConnection.ConnectionString = "Server=" + $YourServerName + ";Database=" + $YourDatabaseName + ";User ID= " + $YourUserName + ";Password=" + $YourDbPassword + ";" 
 

 

 
$DirectoryPath = "C:\FolderName" 
 
$Dep_SqlFiles = get-childitem -Recurse $DirectoryPath -Include "*.sql" 
 

 
$Dep_Info_DataEntry = @(Get-Content $Dep_SqlFiles.FullName) #Get all info of each file and put it in array 
 

 

 

 
foreach($SQLString in $Dep_Info_DataEntry) 
 
{ 
 
    if($SQLString -ne "go") 
 
     { 
 
     #Preparation of SQL packet 
 
     $SQLToDeploy += $SQLString + "`n" 
 
     } 
 
    Else 
 
     { 
 
     try{ 
 
     $SQLCommand = New-Object System.Data.SqlClient.SqlCommand($SQLToDeploy, $SQLConnection) 
 
$SQLCommand.ExecuteNonQuery() 
 
#use this if you want to log the output 
 
#$SQLCommand.ExecuteScalar() | Out-File YourLogFile -Append 
 

 
     } 
 
     Catch 
 
     { 
 

 
     } 
 
    
 
$SQLToDeploy = "" 
 
     } 
 

 
} 
 

 
     

0を下回っていることを別の配列、他の配列にそれを追加します(ここでは、各ラインを追加している)を実行し、「GO」に等しくありません
関連する問題