简体   繁体   English

使用 PowerShell 从 SQL Server 获取整行

[英]Fetch a whole row from SQL Server with PowerShell

So I use ExecuteScalar() to get one value from a table.所以我使用ExecuteScalar()从表中获取一个值。 But how can I get multiple values, ie 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()

One method, using .NET objects in PowerShell, is with a SqlDataAdapter .在 PowerShell 中使用 .NET 对象的一种方法是使用SqlDataAdapter This can load multiple rows and columns into a DataTable for subsequent use.这可以将多个行和列加载到DataTable以供后续使用。

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"]

You can also use a DataReader:您还可以使用 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.我个人不喜欢 SqlDataAdapter 和 DataReaders 因为所有的样板代码。 I think it should have been done in a more elegant way.我认为它应该以更优雅的方式完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM