【问题标题】:PowerShell 2.0 Run one SQL File (having multi SP and Functions)PowerShell 2.0 运行一个 SQL 文件(具有多个 SP 和函数)
【发布时间】:2017-05-06 05:05:14
【问题描述】:

我有一个.sql 文件,其中包含多个存储过程和函数脚本。

我不想使用Invoke 命令,因为我的服务器不支持它们。

目前,如果我的.sql 文件只有一个存储过程或函数,我正在使用以下代码。

$scriptDetail = Get-Content $sqlScriptLocation	| 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()		
$sqlCon.Close()

我正在替换上面代码中的GO 和其他两个命令,因为它们会导致类似的错误

System.Data.SqlClient.SqlException (0x80131904): 'GO' 附近的语法不正确

System.Data.SqlClient.SqlException (0x80131904): 'CREATE FUNCTION' 必须是查询批处理中的第一条语句

必须声明标量变量“@variableName”

【问题讨论】:

  • $sqlScriptLocation = "C:\All_Restore_PROCEDUREFunctiond.sql"

标签: sql sql-server powershell deployment powershell-2.0


【解决方案1】:

经过一番挖掘,我想出了解决方案,读取完整的文件并将其放入一个数组中,然后运行 ​​ForEach 循环,它将获取 ForEach 循环中的每一行,如果它不等于“GO”添加一个条件将它放入另一个数组 else 数组(在其中添加每一行)执行它 代码如下

$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 = ""
      }

}

            

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多