PowerShell功能多个SQL查询以CSV格式输出

时间:2015-03-04 03:43:13

标签: sql sql-server tsql powershell csv

我在让PowerShell运行多个SQL查询并将结果导出为CSV时遇到问题。

我尝试使用Function来完成此操作,但当我希望运行两个查询并输出两个CSV文件时,问题会出现在Process块中。

我尝试创建一个函数来运行查询,第二个函数创建CSV文件但是甚至没有运行SQL查询。我执行此操作时没有安装SQL执行此PowerShell脚本的地方。 -Thanks!

Function Run-Query {
 param([string[]]$queries,[string[]]$sheetnames)
Begin{
 $SQLServer = 'ServerName'
 $Database = 'DataBase'
 $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
 $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
}#End Begin
Process{
 $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
 $SqlCmd.CommandText = $queries
 $SqlCmd.Connection = $SqlConnection
 $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
 $SqlAdapter.SelectCommand = $SqlCmd
 $DataSet = New-Object System.Data.DataSet
 $SqlAdapter.Fill($DataSet)
 $DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path "C:\Scripts\$sheetnames.csv"
}#End Process
End{
 $SqlConnection.Close()
}
}#End function run-query.
$queries = @()
 $queries += @'
Select * from something
'@
 $queries += @'
Select * from something2
'@
$sheetnames = @()
$sheetnames += 'Cert'
$sheetnames += 'Prod'
Run-Query -queries $queries

1 个答案:

答案 0 :(得分:6)

我不确定SQL是否单独处理多个查询,所以当你可能传递两个不同的查询时,SQL服务器可能会将它们解释为一个查询(不是100%肯定会发生这种情况,只是一个猜测)

您已将查询放入数组中,以便我们可以轻松遍历数组,自行运行每个查询并将结果放入CSV格式。

以下是我将如何修改您的代码:

Function Run-Query
{
    param([string[]]$queries,[string[]]$sheetnames)
    Begin
    {
        $SQLServer = 'ServerName'
        $Database = 'DataBase'
        $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
        $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
    }#End Begin
    Process
    {
        # Loop through each query
        For($i = 0; $i -lt $queries.count; $i++)
        {
            $SqlCmd = New-Object System.Data.SqlClient.SqlCommand

            # Use the current index ($i) to get the query
            $SqlCmd.CommandText = $queries[$i]

            $SqlCmd.Connection = $SqlConnection
            $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
            $SqlAdapter.SelectCommand = $SqlCmd
            $DataSet = New-Object System.Data.DataSet
            $SqlAdapter.Fill($DataSet)

            # Use the current index ($i) to get the sheetname for the CSV
            $DataSet.Tables[0] | Export-Csv -NoTypeInformation -Path "C:\Scripts\$($sheetnames[$i]).csv"
        }
    }#End Process
    End
    {
        $SqlConnection.Close()
    }
}#End function run-query.

$queries = @()

$queries += @'
Select * from something
'@
$queries += @'
Select * from something2
'@

$sheetnames = @()
$sheetnames += 'Cert'
$sheetnames += 'Prod'

Run-Query -queries $queries -sheetnames $sheetnames