DBCC CheckDb-any ways to detect errors vb.net?

风格不统一 提交于 2019-12-13 02:58:09

问题


I am using the below code to check if my database has any issues/requires troubleshooting:

Dim cmd As New SqlCommand("DBCC CHECKDB (offpoDb) WITH TABLERESULTS", con)
Dim reader As SqlDataReader = cmd.ExecuteReader
executing.Content = "Checking datatabse for errors"
executing.Margin = New Thickness(243, 111, 0, 0)
While reader.Read
    strBuilder.AppendLine(CStr(reader("MessageText")))
End While
reader.Close()
MessageBox.Show(strBuilder.ToString)

Now, the DBCC CHECKDB command might result in something like this :

CHECKDB found 0 allocation errors and 15 consistency errors in database 'mydb

Which can be fixed the following SQL query :

ALTER DATABASE AdventureWorks2008R2 SET SINGLE_USER WITH ROLLBACK 
IMMEDIATE;
BEGIN TRANSACTION;
DBCC CHECKDB ('AdventureWorks2008R2', REPAIR_ALLOW_DATA_LOSS);
ALTER DATABASE AdventureWorks2008R2 SET MULTI_USER;

But before executing the following query through my application, is there a way to know if DBCC CHECKDB has really returned any errors at all ? Because without any errors, repairing the database will be useless...

Any help ?

AN IDEA THAT CROSSED MY MIND

I was thinking of getting the string from strBuilder to a textbox.The textbox will be checked for the availability of the following line CHECKDB found 0 allocation errors and 15 consistency errors in database..

But this is still not possible because that line can be different from time to time.E.g.

CHECKDB found 0 allocation errors and 15 consistency errors

CHECKDB found 1 allocation errors and 14 consistency errors

Any better ideas ?


回答1:


There are multiple possibilities:

1.
Add NO_INFOMSGS option to the command.
Like this, no records will be returned if no errors are found.

DBCC CHECKDB (dname) WITH TABLERESULTS, NO_INFOMSGS

2.
Read the value(s) of column Level. If one is higher than 10, an error occured. (Reference)
A list of the DBCC-errors you can get with:

SELECT * FROM sys.sysmessages 
WHERE description LIKE '%checkdb%' AND msglangid = 1033 AND severity > 10

3.
Check the result-string for a number higher than 0.

For Each c As Char In "CHECKDB found 0 allocation errors and 15 consistency errors"
    If (Char.IsNumber(c)) AndAlso Integer.Parse(c) > 0 Then
        'Errors occured
    End If
Next


来源:https://stackoverflow.com/questions/47774263/dbcc-checkdb-any-ways-to-detect-errors-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!