Question

I am trying to execute DBCC CHECK DB('MyDB) using ADO.Net, but how can I get the text returned by the command?

I have tried the following:

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);

But the output parameter value is empty.

Was it helpful?

Solution

Maybe this can help you: http://mspowershell.blogspot.com/2008/01/dbcc-check-through-adonetps.html.

EDIT: The link will get you to a blog post that contains the following script:

$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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top