运行多个查询并导出到不同的CSV文件

时间:2015-05-28 21:13:26

标签: powershell csv

我有一个运行sql查询的脚本,如果返回结果,则将这些结果导出到csv文件。我现在需要更进一步,并有类似的东西: - 运行查询1,如果它返回结果保存。运行查询2,如果返回结果保存,则运行查询3,如果返回结果保存。

$server = "Main"
$database = "hellfire"

$query1 = "Select * from mousetrap"
$query2 = "Select * from mickey"
$query3 = "Select * from brimstone"

$templatefile = @"C:\book1.csv"
$savedirectory = @"C:\ExportedFromSQL\Results\"

#Actual Conenction To SQL Server Goes here
#for brevity I am omitting

#check if query returned results
if ($SqlAdapter.Fill($DataSet) - ge 1)
{
    #this is where my catch comes in
    #if $query1 was executed I want to save the file as mouse
    #if $query2 was executed I want to save the file as mi
    #if $query3 was executed I want to save the file as stone

    #$DataSet.Tables[0] | Export-Csv $templatefile -NoTypeInformation
}

1 个答案:

答案 0 :(得分:3)

使用函数运行查询,保持简单,并始终知道您正在执行哪个查询。

Function Execute-SQLquery {
    param ($QueryName, $QueryString, $ResultDir)

    #Actual Conenction To SQL Server Goes here
    #for brevity I am omitting

    if ($SqlAdapter.Fill($DataSet) -ge 1)
    {
        $DataSet.Tables[0] | Export-Csv (join-path $ResultDir ($QueryName + ".csv")) -NoTypeInformation
        return $true
    } else {
        return $false
    }
}

#Call your function
    if (Execute-SQLquery "mousetrap" "Select * from mousetrap" $savedirectory) {
        if (Execute-SQLquery "mickey" "Select * from mickey" $savedirectory) {
            Execute-SQLquery "brimstone" "Select * from brimstone" $savedirectory
        }
    }