从ADO.Net执行DBCC命令

时间:2009-11-04 09:49:56

标签: c# ado.net dbcc

我正在尝试使用ADO.Net执行DBCC CHECK DB('MyDB),但是如何获取该命令返回的文本?

我尝试了以下内容:

SqlCommand sqlCom = new SqlCommand("DBCC CHECKDB ('MyDB')", sqlCon);
SqlParameter output = new SqlParameter();
output.Direction = System.Data.ParameterDirection.ReturnValue;
sqlCom.Parameters.Add(output);
int result = sqlCom.ExecuteNonQuery();
Console.WriteLine(output.Value);

但输出参数值为空。

1 个答案:

答案 0 :(得分:2)

也许这可以帮到你:http://mspowershell.blogspot.com/2008/01/dbcc-check-through-adonetps.html

编辑:该链接将引导您访问包含以下脚本的博文:

$ScriptName = $myInvocation.MyCommand.Name
[void][reflection.assembly]::LoadWithPartialName("System.Data.SqlClient")
$ConnString = "Server=Servername\Instance;Integrated Security=SSPI;Database=DatabaseName;Application Name=$ScriptName"
$MasterConn = new-object ('System.Data.SqlClient.SqlConnection') $ConnString
$MasterCmd = new-object System.Data.SqlClient.SqlCommand 
$MasterCmd.Connection = $MasterConn
$SqlDBCC = "DBCC CHECKDB(master) WITH TABLERESULTS"
$MasterCmd.CommandText = $SqlDBCC
$MasterConn.Open()
$Rset = $MasterCmd.ExecuteReader()
If ($Rset.HasRows -eq $true) {
    While ($Rset.Read()) {
        $line = $Rset["MessageText"]
        If ($Rset["Level"] -gt 10) {
            Write-Host $line -backgroundcolor Yellow -foregroundcolor Red
        } else {
            Write-Host $line 
        }
    }
    $Rset.Close()
}
$MasterConn.Close()