2

I have a script that will run a sql query and if results are returned export those results to a csv file. I need to take that a step further now and have something similar to this: -- Run Query 1, if it returned results save. Run Query 2, if it returned results save, Run Query 3, if it returned results save.

$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
}
3
  • How do you decide which query to run? Commented May 28, 2015 at 21:16
  • @AnsgarWiechers - as long as the correct query is associated with the correct filename they can run in any order. Commented May 28, 2015 at 21:18
  • 1
    Let me repeat the question: how do you decide which query to run? Commented May 28, 2015 at 21:19

1 Answer 1

3

Use a function to run your query, keeps it simple and you always know which query you are executing.

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
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.