使用Powershell从MSSQL数据库中获取行数

时间:2014-07-31 08:25:33

标签: sql-server powershell

我正在尝试将Powershell中的Microsoft SQL数据库表中的行数作为一个整数来解决,并且不应该从Powershell返回的对象中删除数字。

我有;

$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()

现在$ DataSet.Tables [0]在这个实例中返回一个像;

这样的对象
Table Name
-----------

45

我如何才能将45作为int?

3 个答案:

答案 0 :(得分:2)

查看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()

答案 1 :(得分:2)

这是一个基于@ jessehouwing的答案提供两个封装函数的版本。这还处理可选端口,选择TrustedAuth与用户/密码验证以及可选的WHERE子句。

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
}

使用它:

$dbConn = createSqlConnection 'db-server' $null 'myDatabase' $user $password
$count = getRowCount $dbConn 'the_table'

答案 2 :(得分:0)

使用ExecuteScalar是一个更好的解决方案。如果出于某种原因,您希望坚持DataSet使用:

$DataSet.Tables[0].'Table Name'

$DataSet.Tables[0] | Select-Object -ExpandProperty "Table Name"