Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

looping SQL Query within Foreach loop

$
0
0

Hi Guys,

I am trying to merge the values I have in an external file with the result from sql query but there is something that sql query keeps only the result from first loop:

Below is the script I have:

$lines = Get-Content 'c:\firstsecondnames.txt'

$DBs = "192.168.1.1"

$DB = "DBA"

$ConnectionTimeout = 90

$QueryTimeout = 90

 

foreach ($ln in $lines)

    {

 

    $vala  = $line.Split(',')[0]

    $valb  = $line.Split(',')[1]

 

    #DB query

     $Query = "select ValC from dbo.PROCESSED_INTERCHANGES where Firstname = '$vala' and middlename = '$valb'

 

        $conn=new-object System.Data.SqlClient.SQLConnection

    $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $DBs,$DB,$ConnectionTimeout

    $conn.ConnectionString=$ConnectionString

    $conn.Open()

    $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)

    $cmd.CommandTimeout=$QueryTimeout

    $ds=New-Object system.Data.DataSet

    $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)

    [void]$da.fill($ds)

    $conn.Close()

    $conn.Dispose()

    $valC= $row

 

    $fullname = $vala + $valb + $valC

    Write-Host $fullname

}

It is supposed to give me the output something like:

Firsname1Middlename1LastName1

Firsname2Middlename2LastName2

but, what I get is  :

Firsname1Middlename1LastName1

Firsname2Middlename2LastName1

Please let me know if the description of my problem is not clear, thank you very much for your help


Viewing all articles
Browse latest Browse all 6937

Trending Articles