Reputation: 532
I'm trying to get the number of rows from a Microsoft SQL database table in Powershell as an integer and am stuck peeling the figure out of the object Powershell is returning.
I have;
$SQLServer = "MSSQL01" $SQLDBName = "TheTable" $SqlQuery = "select count(*) from cases where opened_date =< '2014-07-30'"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $SqlQuery $SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
Now $DataSet.Tables[0] in this instance returns an object like;
Table Name
-----------
45
How can I grab just the 45 as an int?
Upvotes: 1
Views: 16428
Reputation: 3367
Here's a version which provides two encapsulated functions, based on @jessehouwing's answer. This also handles an optional port, choice of TrustedAuth vs. User/Passwd Authentication, and an optional WHERE clause.
function createSqlConnection($sqlServer, $sqlPort, $dbName, $user, $password) {
$sqlConnection = New-Object System.Data.SqlClient.sqlConnection
if ($sqlPort) { $sqlServer = "$sqlServer,$sqlPort" }
if ($user -and $password) {
$sqlConnection.ConnectionString = "Server=$sqlServer; Database=$dbName; User Id=$user; Password=$password"
} else {
$sqlConnection.ConnectionString = "Server=$sqlServer; Database=$dbName; Integrated Security=True"
}
return $sqlConnection
}
function getRowCount($sqlConnection, $table, $where = "1=1") {
$sqlQuery = "SELECT count(*) FROM $table WHERE $where"
$sqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand($sqlQuery, $sqlConnection)
$row_count = [Int32] $SqlCmd.ExecuteScalar()
$sqlConnection.Close()
return $row_count
}
To use it:
$dbConn = createSqlConnection 'db-server' $null 'myDatabase' $user $password
$count = getRowCount $dbConn 'the_table'
Upvotes: 2
Reputation: 114721
Look at ExecuteScalar
:
$SQLServer = "MSSQL01"
$SQLDBName = "TheTable"
$SqlQuery = "select count(*) from cases where opened_date =< '2014-07-30'"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $SqlQuery $SqlCmd.Connection = $SqlConnection
$SqlConnection.Open()
$Rows= [Int32]$SqlCmd.ExecuteScalar()
$SqlConnection.Close()
Upvotes: 3
Reputation: 10107
Using ExecuteScalar
is a much better solution. If, for some reason, you want to stick with the DataSet
use either:
$DataSet.Tables[0].'Table Name'
or
$DataSet.Tables[0] | Select-Object -ExpandProperty "Table Name"
Upvotes: 1