Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch a whole row from SQL Server with PowerShell

So I use ExecuteScalar() to get one value from a table. But how can I get multiple values, i.e. values from multiple columns.

$connectionString = "Data Source=ServerName;Initial Catalog=DB_Name; Integrated Security=SSPI" 
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection($connectionString)
$query = "select col1, col2, col3 from table where col1= x;" 
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($query, $connection)
$connection.Open()
$NewBatchID = $command.ExecuteScalar() 
$connection.Close()
like image 552
xhr489 Avatar asked Oct 30 '25 08:10

xhr489


2 Answers

One method, using .NET objects in PowerShell, is with a SqlDataAdapter. This can load multiple rows and columns into a DataTable for subsequent use.

This example assumes a single row is returned:

$connectionString = "Data Source=ServerName;Initial Catalog=DB_Name; Integrated Security=SSPI" 
$query = "select col1, col2, col3 from table where col1= x;"

$sqlDataAdapter = New-Object -TypeName System.Data.SqlClient.SqlDataAdapter($query, $connectionString)
$dataTable = New-Object -TypeName System.Data.DataTable
[void]$sqlDataAdapter.Fill($dataTable)
$col1 = $dataTable.Rows[0]["col1"]
$col2 = $dataTable.Rows[0]["col2"]
$col3 = $dataTable.Rows[0]["col3"]
like image 166
Dan Guzman Avatar answered Oct 31 '25 23:10

Dan Guzman


You can also use a DataReader:

$connectionString = "Data Source=ServerName;Initial Catalog=DB_Name; Integrated Security=SSPI" 
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection($connectionString)
$query = "select col1, col2, col3 from table where col1= x;" 
$command = New-Object -TypeName System.Data.SqlClient.SqlCommand($query, $connection)
$connection.Open()

$dataReader = $command.ExecuteReader()
$fieldCount = $dataReader.FieldCount
while ($dataReader.Read()) 
{
    for ($i = 0; $i -lt $fieldCount; $i++) 
    {
        Write-Host "$($dataReader.GetName($i)) is $($dataReader.GetValue($i))." 
    }
}

$connection.Close()

Personally I dislike both SqlDataAdapter and DataReaders because of all the boilerplate code. I think it should have been done in a more elegant way.

like image 23
Palle Due Avatar answered Nov 01 '25 00:11

Palle Due



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!