Loop thru SQL files, second file doesnt run when results are aliased

  • I have a script that loops through *.sql files in a folder. It's OK if I do not alias the column result but will only run the first SQL file if I do use aliases.

    #Loop through the .sql files and run them

    foreach ($filename in get-childitem -path $FolderPath -filter "*.sql" |sort-object) {

    invoke-sqlcmd –ServerInstance $SQLServer -InputFile $filename.fullname

    }

    Two files are currently in the folder.

    The results of ALIASES:

    You

    -------

    Hello World

    The first SQL file:

    select 'Hello World' as [You]

    The second:

    select 'Hello You' as [Me]

    This is SUCCESSFUL when columns not aliased:

    Column1

    -------

    Hello World

    Hello You

    The first SQL file:

    select 'Hello World'

    The second:

    select 'Hello You'

  • Do you get any error or warning messages?

    The absence of evidence is not evidence of absence
    - Martin Rees
    The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
    - Phil Parkin

  • NO, but it did not give the results from the second file.

  • The first execution is defining the output object - a column called 'You'. As the second execution doesn't match that output you don't see it in the results.

    No alias or the same alias you'll get both.

  • This will return the first column from each query, regardless of name:

    $FolderPath = 'C:\users\lyonsg\Documents\Scripts\Powershell\HelloWorldTest\'

    #Loop through the .sql files and run them

    foreach ($filename in get-childitem -path $FolderPath -filter "*.sql" | sort-object) {

    (invoke-sqlcmd –ServerInstance $SQLServer -InputFile $filename.fullname).Item(0)

    }

    If you need more than one column might be more complicated.

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply