Sql 2005 error

В данной статье описана проблема, которая может возникнуть при установке сервера SQL Server 2005. Особенно часто она возникает, если SQL Server 2005 устанавливается из общей сетевой папки или папки на жестком диске, скопированной с установочных компакт-дисков SQL Server 2005.

Ошибка №: 408784 (SQLBUDT)

Проблема

При установке Microsoft SQL Server 2005 появляется следующее сообщение об ошибке:

Во время выполнения мастера установки произошла непредвиденная ошибка. Обратитесь к журналу установки или нажмите кнопку «Справка» для получения дополнительных сведений.

В файл журнала SQLSetupЧисло_Имя_сервера_Core(local).log при этом записывается сообщение об ошибке, приведенное ниже.

Running: InstallToolsAction.10 at: 2006/4/8 16:46:2
Error: Action «InstallToolsAction.10» threw an exception during execution. Error information reported during run:
Target collection includes the local machine.
Fatal Exception caught while installing package: «10»
Error Code: 0x80070002 (2)
Windows Error Text: The system cannot find the file specified. Source File Name: sqlchainingsqlprereqpackagemutator.cpp
Compiler Timestamp: Tue Aug 9 01:14:20 2005
Function Name: sqls::SqlPreReqPackageMutator::modifyRequest
Source Line Number: 196
—- Context ————————————————
sqls::InstallPackageAction::perform
WinException caught while installing package. : 1603
Error Code: 0x80070643 (1603)
Windows Error Text: Fatal error during installation. Source File Name: packageengineinstallpackageaction.cpp
Compiler Timestamp: Fri Jul 1 01:28:25 2005
Function Name: sqls::InstallPackageAction::perform
Source Line Number: 167
—- Context ————————————————

sqls::InstallPackageAction::perform

Примечания

  • Файл SQLSetupЧисло_Имя_сервера_Core(local).log находится в следующей папке:

    C:Program FilesMicrosoft SQL Server90Setup BootstrapLOGFiles

  • Число — это число, которое увеличивается при каждой установке сервера SQL Server 2005. Файл журнала, имя которого включает наибольшее Число, является файлом журнала последней установки SQL Server 2005.

Причина

Данная проблема возникает из-за того, что папки с файлами, необходимыми для установки SQL Server 2005, имеют неверную структуру.

Наиболее часто она возникает при установке SQL Server 2005 из общей сетевой папки или папки на жестком диске, скопированной с установочных компакт-дисков SQL Server 2005.

Временное решение

Чтобы обойти данную проблему, следует исправить структуру папок, используемых для установки SQL Server 2005.

При установке SQL Server 2005 используются две следующие папки:

  • Servers

  • Tools

Обе эти папки должны иметь одинаковый уровень вложенности или находиться в корневом каталоге диска, а их имена не могут быть другими. Папка Servers содержит все файлы, необходимые для установки основных компонентов SQL Server 2005, таких как ядро СУБД. Папка Tools содержит компоненты программных средств и электронную документацию по SQL Server 2005.

Дополнительная информация

Чтобы скопировать файлы с установочных компакт-дисков SQL Server 2005 в папку и установить SQL Server 2005 из этой папки, выполните описанные ниже действия.

Примечание. В данном примере файлы с установочных компакт-дисков SQL Server 2005 копируются в папку D:SQLServer2005.

  1. Создайте в папке D:SQLServer2005 две следующих папки:

    • Servers

    • Tools

  2. Скопируйте все файлы с установочного компакт-диска SQL Server 2005, который называется Servers, в папку D:SQLServer2005Servers.

  3. Скопируйте все файлы с установочного компакт-диска SQL Server 2005, который называется Tools, в папку D:SQLServer2005Tools.

  4. Откройте папку D:SQLServer2005Servers и дважды щелкните файл Setup.exe, чтобы запустить программу установки SQL Server 2005.

Загружаемая с сайта MSDN CTP-версия SQL Server 2005 для разработчиков также состоит из двух файлов. Для выполнения полной установки SQL Server 2005 необходимо загрузить файлы Servers и Tools в одноименные папки, которые должны иметь одинаковый уровень вложенности или находиться в корневом каталоге диска.

Нужна дополнительная помощь?

  • Remove From My Forums
  • Question

  • Hi ,

    Getting below error in SQL error log:

    Error: 17187, Severity: 16, State: 1.
    2011-10-24 00:54:55.06 Logon       SQL Server is not ready to accept new client connections. Wait a few minutes before trying again. If you have access to the error log, look for the informational message that indicates that SQL
    Server is ready before trying to connect again.  [CLIENT: 10.11.10.100]

    Getting below error in SQL Agent:

    SQLServer Error: 258, Unable to complete login process due to delay in prelogin response [SQLSTATE 08001]

    2011-10-11 00:41:40 — ! [382] Logon to server ‘SRVRV1’ failed (ConnAttemptCachableOp)

    Getting below error in EventLog in all of my websvers:

    Description:
    SiteTopicFeed::Load- Timeout expired.  The timeout period elapsed prior to
    completion of the operation or the server is not responding.   at
    System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean
    breakConnection)
       at
    System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObjec
    t stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
       at System.Data.SqlClient.SqlDataReader.get_MetaData()
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
    cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
    cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
    cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
    behavior, String method)
       at System.Data.SqlClient.SqlCommand.ExecuteReader()
       at Norman.SiteTopicFeed.Load(Int32 siteID)

    For more information, see Help and Support Center at
    http://go.microsoft.com/fwlink/events.asp.

    ServerDetails:

    Windows Server 2003 x64 Enterprise Edition

    SQL Server 2005 X86 Standard Edition With SP2

    Please help me how to resolve.

    • Edited by

      Monday, October 24, 2011 12:23 PM
      Mod

Answers

    • Proposed as answer by
      Iric Wen
      Monday, October 31, 2011 1:17 AM
    • Marked as answer by
      Stephanie Lv
      Tuesday, November 1, 2011 7:11 AM

Grant Fritchey steps into the workbench arena, with an example-fuelled examination of catching and gracefully handling errors in SQL 2000 and 2005, including worked examples of the new TRY..CATCH capabilities.

Error handling in SQL Server breaks down into two very distinct situations: you’re handling errors because you’re in SQL Server 2005 or you’re not handling errors because you’re in SQL Server 2000. What’s worse, not all errors in SQL Server, either version, can be handled. I’ll specify where these types of errors come up in each version.

The different types of error handling will be addressed in two different sections. ‘ll be using two different databases for the scripts as well, [pubs] for SQL Server 2000 and [AdventureWorks] for SQL Server 2005.

I’ve broken down the scripts and descriptions into sections. Here is a Table of Contents to allow you to quickly move to the piece of code you’re interested in. Each piece of code will lead with the server version on which it is being run. In this way you can find the section and the code you want quickly and easily.

As always, the intent is that you load this workbench into Query Analyser or Management Studio and try it out for yourself! The workbench script is available in the downloads at the bottom of the article.

  • GENERATING AN ERROR
  • SEVERITY AND EXCEPTION TYPE
  • TRAP AN ERROR
  • USING RAISERROR
  • RETURNING ERROR CODES FROM STORED PROCEDURES
  • TRANSACTIONS AND ERROR TRAPPING
  • EXTENDED 2005 ERROR TRAPPING

SQL Server 2000 – GENERATING AN ERROR

USE pubs

GO

UPDATE dbo.authors

SET zip = ‘!!!’

WHERE au_id = ‘807-91-6654’

/* This will generate an error:

Msg 547, Level 16, State 0, Line 1

The UPDATE statement conflicted with the CHECK constraint  

        «CK__authors__zip__7F60ED59«.

The conflict occurred in database «pubs«,  

        table «dbo.authors«, column ‘zip’.

SQL Server 2005 – GENERATING AN ERROR

USE AdventureWorks;

GO

UPDATE HumanResources.Employee

SET MaritalStatus = ‘H’

WHERE EmployeeID = 100;

/* This generates a familiar error:

Msg 547, Level 16, State 0, Line 1

The UPDATE statement conflicted with the CHECK constraint  

        «CK_Employee_MaritalStatus«.

The conflict occurred in database «AdventureWorks«,

   table «HumanResources.Employee«, column ‘MaritalStatus’.

The statement has been terminated.

SQL Server 2000 AND 2005 – ERROR SEVERITY AND EXCEPTION TYPE

The error message provides several pieces of information:

Msg
A message number identifies the type fo error. Can up to the value of 50000. From that point forward custom user defined error messages can be defined.
Level

The severity level of the error.

  • 10 and lower are informational.
  • 11-16 are errors in code or programming, like the error above.
  • Errors 17-25 are resource or hardware errors.
  • Any error with a severity of 20 or higher will terminate the connection (if not the server).
Line
Defines which line number the error occurred on and can come in extremely handy when troubleshooting large scripts or stored procedures.
Message Text
The informational message returned by SQL Server.

Error messages are defined and stored in the system table sysmessages.

SQL Server 2000 – CATCH AN ERROR

SQL Server 2000 does not allow us to stop this error being returned, but we can try to deal with it in some fashion. The core method for determining if a statement has an error in SQL Server 2000 is the @@ERROR value. When a statement completes, this value is set.

If the value equals zero(0), no error occured. Any other value was the result of an error.

The following TSQL will result in the statement ‘A constraint error has occurred’ being printed,as well as the error.

USE pubs

GO

UPDATE dbo.authors

SET zip = ‘!!!’

WHERE au_id = ‘807-91-6654’

IF @@ERROR = 547

    PRINT ‘A constraint error has occurred’

GO

@@ERROR is reset by each and every statement as it occurs. This means that if we use the exact same code as above, but check the @@ERROR function a second time, it will be different.

UPDATE dbo.authors

SET zip = ‘!!!’

WHERE au_id = ‘807-91-6654’

IF @@ERROR = 547

    PRINT ‘A constraint error has occurred. Error Number:’  

      + CAST(@@ERROR AS VARCHAR)

GO

You will see the error number as returned by the @@ERROR statement as being zero(0), despite the fact that we just had a clearly defined error.

The problem is, while the UPDATE statement did in fact error out, the IF statement executed flawlessly and @@ERROR is reset after each and every statement in SQL Server.

In order to catch and keep these errors, you need to capture the @@ERROR value after each execution.

DECLARE @err INT

UPDATE dbo.authors

SET zip = ‘!!!’

WHERE au_id = ‘807-91-6654’

SET @err = @@ERROR

IF @err = 547

    PRINT ‘A constraint error has occurred. Error Number:’  

      + CAST(@err AS VARCHAR)

GO

Now we can capture the error number and refer to it as often as needed within the code.

SQL Server 2005 – CATCH AN ERROR

While @@ERROR is still available in SQL Server 2005, a new syntax has been added to the T-SQL language, as implemented by Microsoft: TRY... CATCH.

This allows us to finally begin to perform real error trapping.

BEGIN TRY  

    UPDATE HumanResources.Employee

    SET MaritalStatus = ‘H’

    WHERE EmployeeID = 100;

END TRY

BEGIN CATCH

    PRINT ‘Error Handled’;

END CATCH

While there is an error encountered in the code, none is returned to the calling function. In fact, all that will happen in this case is the string 'Error Handled' is returned to the client.

We have actually performed the function of error trapping within TSQL.

There are a number of issues around the use of TRY...CATCH that have to be dealt with, which we will cover later. For example, simply having a TRY...CATCH statement is not enough.

Consider this example:

    UPDATE HumanResources.Employee

    SET ContactID = 19978

    WHERE EmployeeID = 100;

BEGIN TRY  

    UPDATE HumanResources.Employee

    SET MaritalStatus = ‘H’

    WHERE EmployeeID = 100;

END TRY

BEGIN CATCH

    PRINT ‘Error Handled’;

END CATCH

The second error is handled, but the first one is not and we would see this error returned to client application:

Msg 547, LEVEL 16, State 0, Line 1

The UPDATE statement conflicted WITH the FOREIGN KEY CONSTRAINT  

      «FK_Employee_Contact_ContactID«

The conflict occurred IN DATABASE «AdventureWorks«  

      TABLE «Person.Contact« COLUMN ‘ContactID’.

To eliminate this problem place multiple statements within the TRY statement.

SQL Server 2000 – USING RAISERROR

The RAISERROR function is a mechanism for returning to calling applications errors with your own message. It can use system error messages or custom error messages. The basic syntax is easy:

RAISERROR (‘You made a HUGE mistake’,10,1)

To execute RAISERROR you’ll either generate a string, up to 400 characters long, for the message, or you’ll access a message by message id from the master.dbo.sysmessages table.

You also choose the severity of the error raised. Severity levels used in RAISERROR will behave exactly as if the engine itself had generated the error. This means that a SEVERITY of 20 or above will terminate the connection. The last number is an arbitrary value that has to be between 1 and 127.

You can format the message to use variables. This makes it more useful for communicating errors:

RAISERROR(‘You broke the server: %s’,10,1,@@SERVERNAME)

You can use a variety of different variables. You simply have to declare them by data type and remember that, even with variables, you have a 400 character limit. You also have some formatting options.

—Unsigned Integer

RAISERROR(‘The current error number: %u’,10,1,@@ERROR)

—String

RAISERROR(‘The server is: %s’,10,1,@@SERVERNAME)

—Compound String & Integer & limit length of string to first 5  

—characters

RAISERROR(‘The server is: %.5s. The error is: %u’,10,1,

      @@SERVERNAME,@@ERROR)

—String with a minimum and maximum length and formatting to left

RAISERROR(‘The server is: %-7.3s’,10,1,@@SERVERNAME)

A few notes about severity and status. Status can be any number up to 127 and you can make use of it on your client apps. Setting the Status to 127 will cause ISQL and OSQL to return the error number to the operating environment.

— To get the error into the SQL Server Error Log

RAISERROR(‘You encountered an error’,18,1) WITH LOG

— To immediately return the error to the application

RAISERROR(‘You encountered an error’,10,1) WITH NOWAIT

— That also flushes the output buffer so any pending PRINT statements,

— etc., are cleared.

— To use RAISERROR as a debug statement

RAISERROR(‘I made it to this part of the code’,0,1)

SQL SERVER 2005 – USING RAISERROR

The function of RAISERROR in SQL Server 2005 is largely the same as for SQL 2000. However, instead of 400 characters, you have 2047. If you use 2048 or more, then 2044 are displayed along with an ellipsis.

RAISERROR will cause the code to jump from the TRY to the CATCH block.

Because of the new error handling capabilities, RAISERROR can be called in a more efficient manner in SQL Server 2005. This from the Books Online:

BEGIN TRY  

    RAISERROR(‘Major error in TRY block.’,16,1);

END TRY

BEGIN CATCH

    DECLARE @ErrorMessage NVARCHAR(4000),

        @ErrorSeverity INT,

        @ErrorState INT;

    SET @ErrorMessage = ERROR_MESSAGE();

    SET @ErrorSeverity = ERROR_SEVERITY();

    SET @ErrorState = ERROR_STATE();

    RAISERROR(@ErrorMessage,@ErrorSeverity,@ErrorState);

END CATCH;

SQL Server 2000 – RETURNING ERROR CODES FROM STORED PROCEDURES

Stored procedures, by default, return the success of execution as either zero or a number representing the failure of execution, but not necessarily the error number encountered.

CREATE PROCEDURE dbo.GenError

AS

UPDATE dbo.authors

SET zip = ‘!!!’

WHERE au_id = ‘807-91-6654’  

GO

DECLARE @err INT

EXEC @err = GenError

SELECT @err

This will cause an error and the SELECT statement will return a non-zero value. On my machine, -6. In order take control of this, modify the procedure as follows:

ALTER PROCEDURE dbo.GenError

AS

DECLARE @err INT

UPDATE dbo.authors

SET zip = ‘!!!’

WHERE au_id = ‘807-91-6654’

SET @err = @@ERROR

IF @err <> 0

    RETURN @err

ELSE

    RETURN 0

GO

DECLARE @err INT

EXEC @err = GenError

SELECT @err

This time the SELECT @err statement will return the 547 error number in the results. With that, you can begin to create a more appropriate error handling routine that will evolve into a coding best practice within your organization.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

ALTER PROCEDURE dbo.GenError

AS

DECLARE @err INT

UPDATE dbo.authors

SET zip = ‘!!!’

WHERE au_id = ‘807-91-6654’

SET @err = @@ERROR

IF @err <> 0

    BEGIN

        IF @err = 547

            RAISERROR(‘Check Constraint Error occurred’,16,1)

        ELSE

            RAISERROR(‘An unspecified error has occurred.’,10,1)

        RETURN @err

    END

ELSE

    RETURN 0

GO

SQL Server 2005 – RETURNING ERROR CODES FROM STORED PROCEDURES

In order to appropriately handle errors you to know what they are. You may also want to return the errors to the calling application. A number of new functions have been created so that you can appropriately deal with different errors, and log, report, anything you need, the errors that were generated.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

CREATE PROCEDURE GenErr

AS

    BEGIN TRY

        UPDATE HumanResources.Employee

        SET ContactID = 19978

        WHERE EmployeeID = 100;

    END TRY

    BEGIN CATCH

        PRINT ‘Error Number: ‘ + CAST(ERROR_NUMBER() AS VARCHAR);

        PRINT ‘Error Message: ‘ + ERROR_MESSAGE();

        PRINT ‘Error Severity: ‘ + CAST(ERROR_SEVERITY() AS VARCHAR);

        PRINT ‘Error State: ‘ + CAST(ERROR_STATE() AS VARCHAR);

        PRINT ‘Error Line: ‘ + CAST(ERROR_LINE() AS VARCHAR);

        PRINT ‘Error Proc: ‘ + ERROR_PROCEDURE();

    END CATCH

GO

DECLARE @err INT;

EXEC @err = GenErr;

SELECT @err;

When you run the code above, you should receive this on the client, in the message, with a non-zero number in the result set:

(0 row(s) affected)

Error Number: 547

Error Message: The UPDATE statement conflicted WITH the  

           FOREIGN KEY CONSTRAINT

          «FK_Employee_Contact_ContactID«  

           The conflict occurred IN DATABASE

           «AdventureWorks« TABLE «Person.Contact«  

           COLUMN ‘ContactID’.

Error Severity: 16

Error State: 0

Error Line: 4

Error Proc: GenErr

In other words, everything you need to actually deal with errors as they occur.

You’ll also notice that the procedure returned an error value (non-zero) even though we didn’t specify a return code. You can still specify a return value as before if you don’t want to leave it up to the engine.

SQL Server 2000 – TRANSACTIONS AND ERROR TRAPPING

The one area of control we do have in SQL Server 2000 is around the transaction. In SQL Server 2000 you can decide to rollback or not, those are your only options. You need to make decision regarding whether or not to use XACT_ABORT. Setting it to ON will cause an entire transaction to terminate and rollback in the event of any runtime error. if you set it to OFF, then in some cases you can rollback the individual statement within the transaction as opposed to the entire transaction.

Modify the procedure to handle transactions:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

ALTER PROCEDURE dbo.GenError

AS

DECLARE @err INT

BEGIN TRANSACTION

    UPDATE dbo.authors

    SET zip = ‘90210’

    WHERE au_id = ‘807-91-6654’

    SET @err = @@ERROR

    IF @err <> 0

        BEGIN

            IF @err = 547

            PRINT ‘A constraint error has occurred.’

            ELSE

                PRINT ‘An unspecified error has occurred.’

            ROLLBACK TRANSACTION

            RETURN @err

        END

    UPDATE dbo.authors

    SET zip = ‘!!!’

    WHERE au_id = ‘807-91-6654’

    SET @err = @@ERROR

    IF @err <> 0

        BEGIN

            IF @err = 547

                PRINT ‘A constraint error has occurred.’

            ELSE

                PRINT ‘An unspecified error has occurred.’

            ROLLBACK TRANSACTION

            RETURN @err

        END

    ELSE

        BEGIN

            COMMIT TRANSACTION

            RETURN 0

        END

GO

DECLARE @err INT

EXEC @err = GenError

SELECT zip  

FROM dbo.authors

WHERE au_id = ‘807-91-6654’

Since the above code will generate an error on the second statement, the transaction is rolled back as a unit. Switch to the results in order to see that the zip code is, in fact, still 90210. If we wanted to control each update as a seperate statement, in order to get one of them to complete, we could encapsulate each statement in a transaction:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

ALTER PROCEDURE dbo.GenError

AS

DECLARE @err INT

BEGIN TRANSACTION

    UPDATE dbo.authors

    SET zip = ‘90210’

    WHERE au_id = ‘807-91-6654’

    SET @err = @@ERROR

    IF @err <> 0

        BEGIN

            IF @err = 547

            PRINT ‘A constraint error has occurred.’

            ELSE

                PRINT ‘An unspecified error has occurred.’

            ROLLBACK TRANSACTION

            RETURN @err

        END

    ELSE

        COMMIT TRANSACTION

BEGIN TRANSACTION    

    UPDATE dbo.authors

    SET zip = ‘!!!’

    WHERE au_id = ‘807-91-6654’

    SET @err = @@ERROR

    IF @err <> 0

        BEGIN

            IF @err = 547

                PRINT ‘A constraint error has occurred.’

            ELSE

                PRINT ‘An unspecified error has occurred.’

            ROLLBACK TRANSACTION

            RETURN @err

        END

    ELSE

        BEGIN

            COMMIT TRANSACTION

            RETURN 0

        END

GO

DECLARE @err INT

EXEC @err = GenError

SELECT zip  

FROM dbo.authors

WHERE au_id = ‘807-91-6654’

In this case then, the return value will be ‘90210’ since the first update statement will complete successfully. Be sure that whatever mechanism you use to call procedures does not itself begin a transaction as part of the call or the error generated will result in a rollback, regardless of the commit within the procedure. In the next example, we’ll create a transaction that wraps the other two transactions, much as a calling program would. If we then check for errors and commit or rollback based on the general error state, it’s as if the inner transaction that was successful never happened, as the outer transaction rollback undoes all the work within it.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

ALTER PROCEDURE dbo.GenError

AS

DECLARE @err1 INT

DECLARE @err2 INT

BEGIN TRANSACTION

    BEGIN TRANSACTION

        UPDATE dbo.authors

        SET zip = ‘90211’

        WHERE au_id = ‘807-91-6654’

        SET @err1 = @@ERROR

        IF @err1 <> 0

            BEGIN

                IF @err1 = 547

                PRINT ‘A constraint error has occurred.’

                ELSE

                    PRINT ‘An unspecified error has occurred.’

                ROLLBACK TRANSACTION

                RETURN @err1

            END

        ELSE

            COMMIT TRANSACTION

    BEGIN TRANSACTION    

        UPDATE dbo.authors

        SET zip = ‘!!!’

        WHERE au_id = ‘807-91-6654’

        SET @err2 = @@ERROR

        IF @err2 <> 0

            BEGIN

                IF @err2 = 547

                    PRINT ‘A constraint error has occurred.’

                ELSE

                    PRINT ‘An unspecified error has occurred.’

                ROLLBACK TRANSACTION

                RETURN @err2

            END

        ELSE

            BEGIN

                COMMIT TRANSACTION

                RETURN 0

            END

IF (@err1 <> 0) OR (@err2 <> 0)

    ROLLBACK TRANSACTION

ELSE

    COMMIT TRANSACTION

GO

DECLARE @err INT

EXEC @err = GenError

SELECT zip  

FROM dbo.authors

WHERE au_id = ‘807-91-6654’

SQL Server 2005 – TRANSACTIONS AND ERROR TRAPPING

The new error handling changes how transactions are dealt with. You can now check the transaction state using XACT_STATE() function. Transactions can be:

  • Closed (equal to zero (0))
  • Open but unable to commit (-1)
  • Open and able to be committed (1)

From there, you can make a decision as to whether or not a transaction is committed or rolled back. XACT_ABORT works the same way.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

ALTER PROCEDURE GenErr

AS

    BEGIN TRY

        BEGIN TRAN

            UPDATE HumanResources.Employee

            SET ContactID = 1/0

            WHERE EmployeeID = 100;

        COMMIT TRAN

    END TRY

    BEGIN CATCH

        IF (XACT_STATE()) = 1

        BEGIN

            ROLLBACK TRAN;

            RETURN ERROR_NUMBER();

        END

        ELSE IF (XACT_STATE()) = 1

        BEGIN

      —it now depends on the type of error or possibly the line number  

      —of the error

            IF ERROR_NUMBER() = 8134

            BEGIN

                ROLLBACK TRAN;

                RETURN ERROR_NUMBER();

            END

            ELSE

            BEGIN

                COMMIT TRAN;  

                RETURN ERROR_NUMBER();

            END

        END

    END CATCH

GO

DECLARE @err INT;

EXEC @err = GenErr;

SELECT @err;

SQL Server 2005 – EXTENDED 2005 ERROR TRAPPING

With the new TRY...CATCH construct, it’s finally possible to do things about errors, other than just return them. Take for example the dreaded deadlock. Prior to SQL Server 2005, the best you could hope for was to walk through the error messages stored in the log recorded by setting TRACEFLAG values. Now, instead, you can set up a retry mechanism to attempt the query more than once.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

ALTER PROCEDURE GenErr

AS

DECLARE @retry AS tinyint,  

      @retrymax AS tinyint,  

      @retrycount AS tinyint;

SET @retrycount = 0;

SET @retrymax = 2;

SET @retry = 1;

WHILE @retry = 1 AND @retrycount <= @retrymax

BEGIN

    SET @retry = 0;

    BEGIN TRY

        UPDATE HumanResources.Employee

        SET ContactID = ContactID

        WHERE EmployeeID = 100;

    END TRY

    BEGIN CATCH

        IF (ERROR_NUMBER() = 1205)

        BEGIN

            SET @retrycount = @retrycount + 1;

            SET @retry = 1;

        END

    END CATCH

END

GO

DECLARE @err INT;

EXEC @err = GenErr;

SELECT @err;

Поврежденная база данных — это, наверное, один из худших ночных кошмаров большинства администраторов баз данных. Результатом повреждения являются простои, вопли менеджеров и всякие другие неприятные штуки.
В этой статье я объясню что нельзя делать с поврежденной базой данных и опишу кое-что из того, что должно быть сделано, некоторые виды повреждений и как их можно исправить.

Как обнаружить, что база данных повреждена

Обычно повреждения превосходно обнаруживаются при попытке доступа к поврежденной странице. Запросы, бэкапы или процедуры реиндексации завершаются ошибками с высокими уровнями серьезности.
Вот пара примеров системных сообщений при обнаружении повреждения БД:

SQL Server detected a logical consistency-based I/O error: incorrect checksum (expected: 0xfdff74c9; actual: 0xfdff74cb). It occurred during a read of page (1:69965) in database ID 13 at offset 0x0000002229a000 in file ‘D:DevelopDatabasesBroken1.mdf’.

Attempt to fetch logical page 1:69965 in database 13 failed. It belongs to allocation unit 72057594049069056 not to 281474980642816.

Основная проблема заключается в том, что если проверки целостности базы данных не производятся на постоянной основе, то повреждение может быть обнаружено спустя часы, дни и даже месяцы, после того, как оно образовалось, в тот момент, когда уже сложно будет что-то исправить.
Я не буду описывать ситуацию когда база данных перешла в состояние «suspect» («подозрительная» в русской редакции SQL Server — прим. переводчика). Описание всевозможных причин почему база данных может перейти в «suspect» и множества вариантов исправления этого — тема отдельной статьи, если не книги.

Что делать если база данных все-таки повреждена

  1. Не паниковать
  2. Не отсоединять (detach) ее
  3. Не перезапускать SQL Server
  4. Не начинать восстановление сразу
  5. Запустить проверку целостности
  6. Найти причину
Не паниковать

Самое важное, при обнаружении повреждения БД — это не паниковать. Любые принимаемые решения должны быть тщательно взвешаны, во внимание должны быть приняты все возможные факторы. Чертовски просто ухудшить ситуацию приняв не до конца обдуманное решение.

Не отсоединять базу данных

В большинстве случаев, когда SQL Server обнарживает повреждение базы данных, это означает, что в БД на самом деле есть поврежденные страницы. Попытка убедить SQL Server что это не так, путем отсоединения (detach) и повторного присоединения (attach) БД, бэкапа и последующего восстановления, перезапуска службы SQL Server, либо перезагрузки сервера, не приведет к тому, что ошибка исчезнет.
Если база данных повреждена и SQL Server обнаружит это при присоединении, он не сможет присоединить ее. Есть несколько способов заставить его увидеть эту БД, но намного лучше просто не отсоединять ее.

Не перезапускать SQL Server

Точно так же, как при отсоединении-присоединении, перезапуск службы SQL Server не сможет исправить обнаруженные ошибки (если они есть).
Перезапуск службы может сделать ситуацию хуже. Если SQL Server обнаружит ошибки во время выполнения фазы восстановления (recovery) БД после перезапуска, он пометит ее как «suspect», что сильно усложнит процесс восстановления БД.

Не начинать восстановление сразу

У вас может возникнуть соблазн просто запустить DBCC CHECKDB с одним из «восстановительных» параметров (обычно допускающими потерю данных) и надеяться, что все станет лучше (по моему опыту — первое что рекомендуют на «непрофильных» форумах по SQL Server — запустить DBCC CHECKDB REPAIR_ALLOW_DATA_LOSS — прим. переводчика). Во многих случаях запуск такого восстановления не рекомендуется. Он не гарантирует исправления всех ошибок и может привести к недопустимой потере данных.
Такое восстановление — это последний шаг при исправлении ошибок. Оно должно быть запущено только если у вас уже нет другого выбора, но никак не в первую очередь.

Запустить проверку целостности

Для того чтобы решить как исправить базу данных, мы точно должны знать что именно повреждено. Единственный способ, которым мы можем это выяснить — запустить DBCC CHECKDB с параметром All_ErrorMsgs (в SQL Server 2005 SP3, SQL Server 2008 SP1 и в более старших версиях, этот параметр включен по умолчанию, указывать его не обязательно). Помните, что если вы запустите DBCC CHECKDB без параметра No_InfoMsgs, в выводе этой процедуры будет информация о количестве строк и страниц в каждой таблице, что вряд ли будет вас интересовать при анализе ошибок.
DBCC CHECKDB может долго выполняться на больших БД, но необходимо дождаться пока эта процедура не закончит работу. Грамотная стратегия восстановления может быть построена только при наличии информации обо всех проблемах в БД.

Найти причину

После того как ошибки исправлены, работу нельзя считать законченной. Если причина этих ошибок не установлена, они могут возникнуть снова. Обычно, основной причиной ошибок являются проблемы с подсистемой ввода-вывода, но они также могут быть вызваны неправильной работой «низкоуровнего ПО» (вроде антивируса), действиями человека, либо багами самого SQL Server.

Что дальше

Дальнейшие действия по исправлению ошибок целиком и полностью зависят от результатов выполнения CheckDB. Чуть дальше я покажу несколько наиболее часто возникающих ошибок (учтите, что эта статья не претендует на звание полного описания всевозможных ошибок).
Описанные ошибки располагаются по возрастанию уровня серьезности — от наименее серьезных к наиболее серьезным. В общем-то, для наиболее серьезных ошибок, находимых CheckDB, есть описание доступных методов их резрешения.
Если у вас вдруг обнаружится ошибка не описанная в статье, обратите внимание на последний раздел — «Поиск помощи».

Неверная информация о свободном месте на странице

Msg 2508, Level 16, State 3, Line 1
The In-row data RSVD page count for object «Broken1», index ID 0, partition ID 76911687695381, alloc unit ID 76911687695381 (type In-row data) is incorrect. Run DBCC UPDATEUSAGE.

В SQL Server 2000, количество строк и страниц в таблице или индексе, хранящееся в метаданных, могло не соответствовать действительности (и даже быть отрицательным) и DBCC CHECKDB не видел в этом ничего плохого. В SQL Server 2005, это количество должно быть правильным и CheckDB выдаст предупреждение, если вдруг найдет несоответствие.
Это несерьезная прблема и очень легко разрешается. Как говорится в сообщении, нужно всего лишь запустить DBCC UPDATEUSAGE в контексте нужной БД и предупреждение исчезнет. Эта ошибка часто встречается в базах данных обновленных с SQL Server 2000 и не должна появляться в базах данных, созданных в SQL Server 2005/2008.

Msg 8914, Level 16, State 1, Line 1
Incorrect PFS free space information for page (1:26839) in object ID 181575685, index ID 1, partition ID 293374720802816, alloc unit ID 76911687695381 (type LOB data). Expected value 0_PCT_FULL, actual value 100_PCT_FULL.

Эта ошибка появляется, когда PFS-страница (Page Free Space), которая учитывает насколько заполнены страницы в БД, содержит некорректные значения. Эта ошибка, как и упомянутая ранее, не является серьезной. Алгоритм, по которому определялось насколько заполнены страницы, в SQL Server 2000 не всегда отрабатывал правильно. Для решения этой проблемы нужно запустить DBCC CHECKDB с параметром REPAIR_ALLOW_DATA_LOSS и, если это единственная ошибка в БД, никакие данные, на самом деле, не пострадают.

Повреждение только некластерных индексов

Если все ошибки, найденные CheckDB, относятся к индексам с ID = 2 и больше, это означет, что были повреждены только некластерные индексы. Поскольку информация, содержащаяся в некластерных индексах, является «избыточной» (те же самые данные хранятся в куче, либо в кластерном индексе — прим. переводчика), эти повреждения могут быть исправлены без потери каких-либо данных.
Если все ошибки, найденные CheckDB, относятся к некластерным индексам, рекомендуемый «уровень восстановления» для DBCC CHECKDB — REPAIR_REBUILD. Примеры таких ошибок (на самом деле ошибок такого типа намного больше):

Msg 8941, Level 16, State 1, Line 1
Table error: Object ID 181575685, index ID 4, page (3:224866). Test (sorted [i].offset >= PAGEHEADSIZE) failed. Slot 159, offset 0x1 is invalid.

Msg 8942, Level 16, State 1, Line 1
Table error: Object ID 181575685, index ID 4, page (3:224866). Test (sorted[i].offset >= max) failed. Slot 0, offset 0x9f overlaps with the prior row.

В этом случае, повреждение может быть полностью исправлено удалением поврежденных некластерных индексов и повторным их созданием. Перестроение индекса (ALTER INDEX REBUILD) в режиме on-line (и иногда в off-line) читает страницы старого индекса для создания нового и, следовательно, завершится с ошибкой. Поэтому, необходимо удалить старые индексы и создать их заново.
Именно это сделает DBCC CHECKDB с параметром REPAIR_REBUILD, но база данных при этом должна быть в однопользовательском режиме. Вот почему обычно лучше вручную выполнить эти операции, чтобы с базой данных можно было продолжать работать, пока индексы будут пересоздаваться.
Если у вас недостаточно времени на то, чтобы пересоздать нужные индексы и в наличии есть «чистый» (не содержащий в себе ошибок) полный бэкап и бэкапы журнала транзакций с неразорванной цепочкой журналов, вы можете восстановить поврежденные страницы из них.

Повреждение LOB-страниц

Msg 8964, Level 16, State 1, Line 1
Table error: Object ID 181575685, index ID 1, partition ID 72057594145669120, alloc unit ID 72057594087800832 (type LOB data). The off-row data node at page (1:2444050), slot 0, text ID 901891555328 is not referenced.

Ошибка говорит о том, что существуют LOB-страницы (Large OBject), на которые не ссылается ни одна страница с данными. Такое может произойти, если ранее был поврежден кластерный индекс (или куча) и его поврежденные страницы были удалены.
Если CheckDB говорит только о таких ошибках, то можно запускать DBCC CHECKDB с параметром REPAIR_ALLOW_DATA_LOSS — эти страницы будут уничтожены. Поскольку у вас все равно нет страниц с данными, которые ссылаются на эти страницы, бОльшей потери данных уже не будет.

Ошибки, связанные с выходом за пределы допустимого диапазона

Msg 2570, Sev 16, State 3, Line 17
Page (1:1103587), slot 24 in object ID 34, index ID 1, partition ID 281474978938880, alloc unit ID 281474978938880 (type «In-row data»). Column «modified» value is out of range for data type «datetime». Update column to a legal value.

Эти ошибки показывают, что в столбце есть значения выходящие за пределы допустимого диапазона. Это может быть значение типа datetime, предполагающее, что с полуночи прошло больше 1440 минут, строка-Unicode, в которой количество байт не делится на 2, или float/real с неверным значением точности.
Проверка на эти ошибки не выполняется по умолчанию, для баз данных обновленных с версии SQL Server 2000 или более ранних, если перед этим ни разу не выполнялась команда DBCC CHECKDB со включенным параметром DATA_PURITY.
CheckDB не сможет исправить эти ошибки, поскольку неизвестно какие значения поставить взамен неправильных. Исправление таких ошибок не требует особых усилий, но выполняется вручную. Неправильные значения должны быть заменены на что-нибудь приемлимое. Основная проблема — это поиск неверных значений. В этой статье базы знаний есть пошаговая инструкция.

Повреждение кластерного индекса или кучи

Если обнаруживается, что повреждены страницы кучи или листового уровня (leaf pages) кластерного индекса — это означает, что данные на них потеряны. Страницы листового уровня кластерного индекса содержат непосредственно страницы данных и для них избыточность никак не обеспечивается.
Если CheckDB сообщает о повреждении страниц листового уровня кластерного индекса, необходимый «уровень восстановления» для DBCC CHECKDB — REPAIR_ALLOW_DATA_LOSS.
Примеры таких ошибок:

Server: Msg 8976, Level 16, State 1, Line 2
Table error: Object ID 181575685, index ID 1, partition ID 76911687695381, alloc unit ID 76911687695381 (type In-row data). Page (1:22417) was not seen in the scan although its parent (1:479) and previous (1:715544) refer to it.

Server: Msg 8939, Level 16, State 1, Line 2
Table error: Object ID 181575685, index ID 0, page (1:168576). Test (m_freeData >= PAGEHEADSIZE && m_freeData <= (UINT)PAGESIZE — m_slotCnt * sizeof (Slot)) failed. Values are 44 and 8028.

Следует помнить, что если ошибки, возвращаемые CheckDB, относятся к index id = 0 или 1, это значит, что повреждены непосредственно данные.
Такой тип ошибок исправляется, но исправление заключается в уничтожении строк или целых страниц. Когда CheckDB удаляет данные для исправления ошибки, ограничения, налагаемые внешними ключами, не проверяются и никакие триггеры не срабатывают. Строки или страницы просто удаляются. В результате данные могут оказаться не согласованными, либо может быть нарушена логическая целостность (на LOB-страницы может больше не ссылаться ни одна строка, либо строки некластерного индекса могут указывать «в никуда»). Из-за таких последствий, подобное восстановление, не рекомендуется использовать.
Если у вас есть «чистый» бэкап, восстановление из него обычно является более предпочительным, для исправления таких ошибок. Если база данных находится в полной модели восстановления и у вас есть бэкапы журнала транзакций с неразорванной цепочкой журналов (начиная с последнего «чистого» полного бэкапа), вы можете сделать бэкап активной части лога и восстановить базу данных целиком (или только поврежденные страницы), в результате чего данные вообще не будут потеряны.
Если бэкапа с неповрежденными данными нет, у вас остается только один вариант — запуск DBCC CHECKDB с параметром REPAIR_ALLOW_DATA_LOSS. Это потребует перевода базы данных в однопользовательский режим на все время выполнения этой процедуры.
И хотя у вас нет возможности избежать потери данных, вы можете посмотреть какие данные будут удалены из кластерного индекса. Для этого, посмотрите этот пост Пола Рэнадала.

Повреждение метаданных

Msg 3853, Level 16, State 1, Line 1
Attribute (object_id=181575685) of row (object_id=181575685,column_id=1) in sys.columns does not have a matching row (object_id=181575685) in sys.objects.

Подобные ошибки, обычно, возникают в базах данных, обновленных с SQL Server 2000, когда кто-то ковырялся напрямую в системных таблицах.
В системных таблицах любой версии SQL Server внешние ключи не используются, поэтому в SQL Server 2000 была возможность удалить строку из sysobjects (например, таблицу) и оставить в таблицах syscolumns и sysindexes строки, ссылающиеся на удаленную строку.
В SQL Server 2000 CheckDB не проверял целостность системного каталога и такие проблемы зачастую висели незамеченными. В SQL Server 2005, CheckDB проверяет целостность системного каталога и такие ошибки могут проявиться.
Исправление этих ошибок дело не самое легкое. CheckDB не может их исправить, поскольку единственное что можно сделать — это удалить записи из системных таблиц, что, в свою очередь, может вызвать потерю большого количества данных. Если у вас есть бэкап этой БД, сделанный до обновления на SQL Server 2005 и обновление было совсем недавно, вы можете развернуть его на SQL Server 2000, на нем вручную подправить системные таблицы и снова перенести БД на SQL Server 2005.
Если у вас нет бэкапа БД на SQL Server 2000 или обновление прошло слишком давно и потеря данных неприемлима, есть два пути. Первый — отредактировать системные таблицы в SQL Server 2005, но следует учитывать, что это довольно сложный и рискованный процесс, поскольку системные таблицы не документированы и гораздо более сложны, чем в ранних версиях. В этом посте можно найти дополнительную информацию.
Второй путь — это заскриптовать все объекты БД и экспортировать все данные, после чего создать новую базу данных, восстановить объекты и залить данные. Этот вариант более предпочтителен.

Неисправимые повреждения

CheckDB не может исправить все. Любые ошибки вроде приведенных ниже неисправимы и единственный вариант — это восстановление базы данных из бэкапа, в котором нет этих повреждений. Если у вас есть полный бэкап и цепочка журналов не нарушена до текущего времени, вы можете забэкапить заключительный фрагмент журнала транзакций и база данных может быть восстановлена без потери каких-либо данных.
Если таких бэкапов нет, единственное что вы можете сделать — заскриптовать те объекты и выгрузить те данные, которые еще доступны. Вполне вероятно, что из-за повреждений не все данные будут доступны, и, скорее всего, не все объекты смогут быть заскриптованы без ошибок.

Повреждение системных таблиц

Msg 7985, Level 16, State 2, Line 1
System table pre-checks: Object ID 4. Could not read and latch page (1:358) with latch type SH.
Check statement terminated due to unrepairable error.

Msg 8921, Level 16, State 1, Line 1
Check terminated. A failure was detected while collecting facts. Possibly tempdb out of space or a system table is inconsistent.

CheckDB зависит от нескольких критически важных системных таблиц, для того чтобы получить представление о том, что должно быть в базе данных. Если сами эти таблицы повреждены, то CheckDB не может даже предположить что должно быть в базе данных и с чем сравнить текущее положение дел, не говоря уже о том, чтобы что-то исправить.

Повреждение «карт распределения»

Msg 8946, Level 16, State 12, Line 1
Table error: Allocation page (1:2264640) has invalid PFS_PAGE page header values. Type is 0. Check type, alloc unit ID and page ID on the page.

Msg 8998, Level 16, State 2, Line 1
Page errors on the GAM, SGAM, or PFS pages prevent allocation integrity checks in database ID 13 pages from (1:2264640) to (1:2272727)

В этом случае, одна или несколько страниц определяющих размещение данных в БД (карты распределения — прим. переводчика) повреждены. Эти страницы используются для того чтобы определять какие страницы и экстенты в БД используются, а какие свободны. CheckDB не может исправить такие ошибки, поскольку практически невозможно определить (без этих страниц) какие экстенты используются для размещения данных, а какие нет. Простое удаление такой «карты распределения» невозможно, поскольку удаление любой из них повлечет за собой удаление 4 GB данных.

Поиск помощи

Если вы не уверены в том что вам нужно сделать — обратитесь за помощью. Если вдруг вы получаете сообщение о повреждении БД, которое вам непонятно и которое не описано выше — обратитесь за помощью. Если вы не уверены в том, что выбрали наилучший метод восстановления — обратитесь за помощью.
Если у вас есть Senior DBA, обратитесь к нему. Если у вас есть «наставник» — спросите у него. Спросите совета на форумах, но помните, что не все советы полученные на форумах полезны. На самом деле, именно там время от времени публикуются абсолютно неправильные и даже опасные решения.
Обратитесь в службу поддержки Microsoft, наконец. Это будет небесплатно, но они действительно знают что можно сделать с поврежденной базой данных и вполне вероятно, что если ваша база данных критична для предприятия, то стоимость простоя во время самостоятельного поиска решения будет намного выше чем стоимость обращения в саппорт.

Заключение

В этой статье я дал несколько примеров того, что можно сделать при обнаружении поврежденной БД и, что даже важнее, того, что делать не надо. Надеюсь, что теперь вы лучше понимаете какие методы можно применять для решения описанных проблем и насколько важно иметь хорошие бэкапы (и правильно выбрать модель восстановления — прим. переводчика).

Примечание: это мой первый перевод, который, к тому же делался не за раз, а в несколько подходов, вечерами, когда появлялось свободное время, поэтому текст целиком, возможно, кому-то покажется несколько несогласованым. Если где-то я был излишне косноязычен и какая-то часть текста вдруг окажется трудной для понимания — с радостью выслушаю все замечания.
С уважением, unfilled.
P.S. Когда я уже собрался было нажать на кнопочку «Опубликовать», мне на почту свалилась рассылка от SQL Server Central с вот таким вот комиксом.

Table of Contents

  • Introduction
  • When We Need To Handle Error in SQL Server
  • Error Handling Mechanism
  • Using @@ERROR
    • General Syntax
    • Return Type
    • Sample Example 
    • When We Should Use @@Error
  • Using Try…Catch Block
    • General Syntax
    • Sample Example
    • Nested TRY-CATCH Block
    • Try-Catch Block for Transaction Roll Back
  • Future Study
  • History

Introduction

During development of any application, one of the most common things we need to take care of is Exception and Error handling. Similarly we need to take care of handling error and exception while designing our database like inside stored procedure. In SQL Server 2005, there are some beautiful features available using which we can handle the error.

When We Need To Handle Error in SQL Server

Generally a developer tries to handle all kinds of exception from the code itself. But sometimes we need to handle the same from the DB site itself. There are some scenarios like, we are expecting some rows should come when we will execute the store procedure, but unfortunately SP returns none of them. Below points can be some possible scenarios where we can use error handling:

  • While executing some DML Statement like INSERT, DELETE, UPDATE we can handle the error for checking proper output
  • If transaction fails, then we need to rollback — This can be done by error handling
  • While using Cursor in SQL Server

Error Handling Mechanism

The two most common mechanisms for error handling in SQL Server 2005 are:

  • @@ERROR
  • TRY-CATCH Block

Let’s have a look at how we can implement both @@Error and TryCatch block to handle the error in SQL Server 2005.

Using @@ERROR

We can consider @@ERROR as one of the basic error handling mechanisms in SQL Server. @@Error is a Global Variable in SQL Server. This variable automatically populates the error message when a certain error occurred in any statement. But we have to trace it within just after the next line where the actual error occurred, otherwise, it will reset to 0.

General Syntax

General syntax for @@ERROR is as follows:

Select @@ERROR

Return Type

int

It returns the Error Number.

Sample Example

I have a table named StudentDetails with columns, Roll (int), Name (varchar) and Address (varchar). Now I am intentionally trying to insert a char in Roll field:

insert into StudentDetails (roll,[Name],Address)
 values ('a','Abhijit','India')

This will throw the following Error :

Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'a' to data type int.

Check out the Message and number, it is 245. Now, I am executing the @@Error statement just after this statement and check out the output:

Select  @@Error 

The output is:

Error1.JPG

So, @@Error returns the same error as return by insert command. As I have already said, @@Error returns the error number for the last Transact-SQL statement executed, so if we execute any @@Error statement, we will get output 0.

When We Should Use @@Error 

There are some scenarios where we should use @@ERROR:

  • With Insert, Delete, Update, Select Into Statement
  • While using Cursor in SQL Server (Open, Fetch Cursor)
  • While executing any Stored Procedure

Using Try…Catch Block

This is available from SQL Server 2005 Onwards. This is generally used where want to trap or catch error for multiple SQL statements like or a SQL Block of statement. TRY...CATCH blocks are the standard approach to exception handling in modern programming languages. Use and syntax are likely the same as normal programming language. Like Exception Handling in Programming Language, we can use nested TryCatch block in SQL Server also.

Try block will catch the error and will throw it in the Catch block. Catch block then handles the scenario.

GeneralBlock.JPG

General Syntax

Below is the general syntax for Try-Catch block:


BEGIN TRY
   
END TRY
BEGIN CATCH
   
END CATCH

Whenever there are some errors in TRY Block, execution will moved to CATCH block.

Sample Example

As I have already discussed about the studentDetails table, I am now going to insert one record in the table with Roll='a'.

BEGIN TRY
     INSERT INTO StudentDetails(Roll, [Name])
     VALUES('a', 'Abhijit')
END TRY
BEGIN CATCH
   SELECT 'There was an error while  Inserting records in DB '
END CATCH

As Roll is an int type but I am trying to insert a char type data which will violate the type conversion rule, an error will be thrown. So the execution pointer will jump to Catch block. And below is the output:

There was an error while  Inserting records in DB

Now, to get the details of the error SQL Server provides the following System function that we can use inside our Catch-block for retrieving the details of the error. Please check the below table:

Function Name Description
ERROR_MESSAGE() Returns the complete description of the error message
ERROR_NUMBER() Returns the number of the error
ERROR_SEVERITY() Returns the number of the Severity
ERROR_STATE() Returns the error state number
ERROR_PROCEDURE() Returns the name of the stored procedure where the error occurred
ERROR_LINE() Returns the line number that caused the error

Here is one simple example of using System Function:

BEGIN TRY
   INSERT INTO StudentDetails(Roll, [Name])
    VALUES('a', 'Abhijit')
END TRY
BEGIN CATCH
   SELECT  ' Error Message: '  + ERROR_MESSAGE() as ErrorDescription
END CATCH

I have executed the same code block here but rather than showing custom message, I am showing the internal Error message by Calling ERROR_MESSAGE() System function. Below is the output:

SystemFunction.JPG

Nested TRY-CATCH Block 

Like other programming languages, we can use Nested Try catch block in SQL Server 2005.

BEGIN TRY
  print 'At Outer Try Block'
   BEGIN TRY
      print 'At Inner Try Block'
   END TRY
   BEGIN CATCH
      print 'At Inner catch Block'
   END CATCH
END TRY
BEGIN CATCH
   print 'At Outer catch block'
END CATCH

If we execute this, the output will look like:

At Outer Try Block
At Inner Try Block

Now, Inner catch blocks throw an error:

BEGIN TRY
  print 'At Outer Try Block'
   BEGIN TRY
      print 'At Inner Try Block'
      INSERT INTO StudentDetails(Roll, [Name])   _
		VALUES('a', 'Abhijit')  
   END TRY
   BEGIN CATCH
      print 'At Inner catch Block'
   END CATCH
END TRY
BEGIN CATCH
   print 'At Outer catch block'
END CATCH

Which gives the following output:

At Outer Try Block
At Inner Try Block
At Inner catch Block

Try-Catch Block For Transaction Roll Back 

Here I am going to explain one real life scenario of using TRY-CATCH block. One of the common scenarios is using Transaction. In a Transaction, we can have multiple operations. If all operations executed successfully, then database will commit otherwise we need to ROLLBACK.

BEGIN TRY
   
   BEGIN TRANSACTION   

   
   DELETE FROM StudentDetails WHERE Roll = '1'
   Print 'Delete Record from Student Details Table'
   
   DELETE FROM Library  WHERE Roll = 'a'
   Print 'Delete Record from Library Table'
   
   COMMIT
   
   Insert into LogDetails(ID,Details) values ('1','Transaction Successful');
END TRY
BEGIN CATCH
 Print 'Transaction Failed - Will Rollback'
  
  IF @@TRANCOUNT > 0
    ROLLBACK  
END CATCH

Below is the output:

Delete Record from Student Details Table
Transaction Failed - Will Rollback

Points of Interest

I have written and explained each and every thing very easily and with a practical example. Hope this will help you.

Please give your feedback and suggestions.

Future Study

Here is one of the good links for future reference for SQL Server 2005 Error Handling:

  • Error Handling in SQL Server – A Background [^]

History

  • Initial post : 1st August, 2009

I’ve been trying to install Ms SQL Server 2005 for over two weeks now, and I’ve finally gotten to the point where the prerequisites all seem to be in place. Unfortunately, every time I try to install SQL Server itself, I get the following message:

“The SQL Server service failed to start. For more information, see the SQL Server Books Online topics, «How to: View SQL Server 2005 Setup Log Files» and «Starting SQL Server Manually.»”

The installer then “rolls back” the install and I’m left with three uninstalled products in the Setup list: “SQL Server Database Services,” “Reporting Services,” and “Workstation Components, Books Online…”.

Does anyone have any thoughts? I can’t check the SQL Server Books Online topics because they don’t install, either; and I can’t make sense of the log files without them.

Thanks!

raven's user avatar

raven

17.8k16 gold badges80 silver badges112 bronze badges

asked Sep 15, 2008 at 13:45

4

I had similar problem while installing SQL Server 2005 on Windows 7 Professional and got error SQL server failed to start. I logged in as a Administrator (my user id is administrator) in windows.

SOLUTION

  1. Go to services, from control panel -> Administrative Tools

  2. Click on properties of «SQL Server (MSSQLSERVER)»

  3. Go to Log On Tab, Select «This Account»

  4. Enter your windows login detail (administrator and password)

  5. Start the service manually, it should work fine..

Hope this too helps..

Aleš's user avatar

Aleš

8,8167 gold badges64 silver badges107 bronze badges

answered Apr 11, 2013 at 23:53

Tilesh Khatri's user avatar

It looks like not all of your prerequisites are really working as they should be. Also, you’ll want to make sure that you are installing from the console itself and not through any kind of remote session at all. (I know, this is a pain in the a@@, but sometimes it makes a difference.)

You can acess the SQL Server 2005 Books Online on the Web at: http://msdn.microsoft.com/en-us/library/ms130214(SQL.90).aspx. This documentation should help you decipher the logs.

Bonus tidbit: Once you get that far, if you plan on installing SP2 without getting an installation that fails and rolls back, another little pearl of wisdom is described here:
http://blog.andreloker.de/post/2008/07/17/SQL-Server-hotfix-KB948109-fails-with-error-1920.aspx. (My issue was that the «SQL Server VSS Writer» (Service) was not even installed.) Good luck!

answered Sep 15, 2008 at 14:41

solution for the microsoft sql server 2005 failed to start

  1. Read carefully all the tabs and icon name when you open it
  2. Don’t be in a hurry be cool and do this procedure
  3. Start your sql and proceed further when u get this error than start with this solution . do not quit the installation
    start->control panel—>administrative tools—>services—>in services search for the sql server (sql express) —>click on logon (tab)—> check local system account & also check
    service to interact with desktop —>click on recovery tab —>first failure choose restart the service ;second failure —> run the program —> apply ok

Martin Smith's user avatar

Martin Smith

430k87 gold badges727 silver badges825 bronze badges

answered Jan 29, 2014 at 15:59

REHAN SHAIKH's user avatar

While that error message is on the screen (before the rollback begins) go to Control Panel -> Administrative Tools -> Services and see if the service is actually installed. Also check what account it is using to run as. If it’s not using Local System, then double and triple check that the account it’s using has rights to the program directory where MS SQL installed to.

answered Sep 15, 2008 at 13:51

DougN's user avatar

DougNDougN

4,32711 gold badges56 silver badges81 bronze badges

We had a similar problem recently withour running SQL 2005 servers (more specifically: The reporting services). The windows services didn’t start anymore with no real error message whatsoever.

I found out that this problem was related to some KB hotfixes that have been deployed lately. For some reason those hotfixes resulted in the services taking longer than usually for starting up.

Since by default, there is a timeout that kills the service after 30 seconds when it was not able to go beyond the start methods, this was the reason why it simply terminated.

Maybe this is what you are experiencing.

Theres a work around described on Microsoft Connect (link). Although the hotfixes listed in this article didn’t match the ones that have been deployed to our systems, the workaround worked for us.

answered Oct 1, 2008 at 10:12

Mephisztoe's user avatar

MephisztoeMephisztoe

3,2067 gold badges34 silver badges48 bronze badges

I’d try just installing the tools and database services to start with. leave analysis, Rs etc and see if you get further. I do remeber having issues with failed installs so be sure to go into add/remove programs and remove all the pieces that the uninstaller is leaving behind

answered Oct 28, 2008 at 4:13

CPU_BUSY's user avatar

CPU_BUSYCPU_BUSY

7812 gold badges5 silver badges15 bronze badges

I have seen something similar before when the account the SQL Server is set to run under does not have the required permission.

Tangentially, once it is installed, a common mistake is to change the login credentials from Windows Services, not from SQL Server Configuration Manager. Although they look the same, the SQL Server tool grants access to some registry keys that the Windows tool does not, which can cause a problem on service startup.

You can run Sysinternals RegMon/Sysinternals ProcessMon while the install is running, filtering by sqlsevr.exe and Failure messages to see if the account credentials are a problem.

Hope this helps

answered Oct 28, 2008 at 13:05

James Green's user avatar

James GreenJames Green

1,8171 gold badge14 silver badges13 bronze badges

I agree with Greg that the log is the best place to start. We’ve experienced something similar and the fix was to ensure that admins have full permissions to the registry location HKLMSystemCurrentControlSetControlWMISecurity prior to starting the installation. HTH.

answered Nov 3, 2008 at 19:41

Eric Sabine's user avatar

Eric SabineEric Sabine

1,1557 silver badges8 bronze badges

Перечень проблем, возникающих при установке и первоначальной настройке MS SQL Server 2005 на Windows Server 2008, которые встречались на моей практике чаще всего:

  • При установке SQL Server 2005 нет возможности установить Report Services (в мастере установки недоступна опция) либо не устанавливаются клиентские компоненты и прочие дополнительные модули
  • Остановка процесса установки MS SQL Server 2005 на стадии Setting File Security
  • Нет возможности установить Report Services т.к. в программе установки включение этой опции недоступно.
  • После установки SQL Server 2005 отказывается стартовать служба полнотекстового поиска — SQL Server FullText Search
  • После установки SP3 для SQL Server 2005 служба SQL Server Reporting Services не стартует с описанием ошибки об истечении таймаута запуска 
  • После установки SP3 на SQL Server может потеряться доступность вэбузла SQL 2005 Reporting Service

При установке SQL Server 2005 нет возможности установить Report Services (в мастере установки недоступна опция) либо не устанавливаются клиентские компоненты и прочие дополнительные модули

Сценарий с которыми приходилось сталкиваться:

В мастере установки SQL Server 2005 отмечаются для установки клиентские модули и утилиты управления и настройки, в том числе SQL Server Management Studio, но после окончания установки эти модули в системе отсутствуют.

Причина и решение проблем:

Вероятнее всего установка производится с архивного носителя (не с оригинального инсталляционного CD).
К примеру в архивной поставке RTM версия SQL Server 2005 x64 English Standard Edition мы имеем два архива:

SW_CD_SQL_Svr_Standard_Edtn_2005_64Bit_X64_English_1_x64_MLF_X11-57664.EXE
SW_CD_SQL_Svr_Standard_Edtn_2005_64Bit_X64_English_2_x64_MLF_X11-57665.EXE

В первом архиве находятся файлы необходимые для установки самого движка SQL Server, а во втором всевозможные к нему добавы типа Report Services, SQL Server Management Studio и т.п…
Так вот архитектура инсталлятора SQL Server подразумевает то, что эти два архива перед установкой будут распакованы в соответствующие каталоги с конкретными именами: Servers и Tools
И при этом ещё эти каталоги должны находиться вместе в одном каталоге. Только в таком случае можно будет гарантировать успешный и правильный исход программы установки.
Кажется полным бредом…но тем не менее это факт проверенный на практике.

Остановка процесса установки MS SQL Server 2005 на стадии Setting File Security

При попытке установить MS SQL Server 2005 x64 на Windows Server 2008 Standard x64 столкнулся с проблемой — программа установки «замерзает» на шаге «Setting File Security»

image

В этот момент статусном логе установки можно наблюдать последние записи что-то типа:

 <EndFunc Name=’SetCAContext’ Return=’T’ GetLastError=’203′>
Doing Action: Write_sqlRegSDDL
PerfTime Start: Write_sqlRegSDDL : Tue Feb 24 15:00:07 2009

Как оказалось эта проблема связана с тем что для текущего домена в котором выполняется установка существуют
доверительные отношения с другими доменами и в некоторых случаях процесс установки из-за этого может затягиваться более чем на сутки
на стадии «Setting File Security». В общем-то проблема описана в статье
MS KB 910070
Таже приводится весьма  замороченный способ исправления проблемы с манипуляциями по пропатчиванию msi пакетов программ инсталляции SQL Server 2005.

Бойцами невидимого фронта опытным путём было выяснено что в момент “замерзания” программы установки достаточно выключить сетевой интерфейс чтобы имитировать пропадание сетевого подключения, после чего (у меня получилось примерно 10 минут) программа установки как ни в чём не бывало продолжит свою работу.

Бойцы невидимого фронта:

  • MSDN Forums — Problem installing sql server express

  • SimonS Blog on SQL Server Stuff — SQL 2005 install hangs on «Setting File Security»

Нет возможности установить Report Services т.к. в программе установки включение этой опции недоступно

Как известно компонент Microsoft SQL Server 2005 — Report Services требует наличие прeдустановленных служб IIS.
При включении роли Вэб-сервер (IIS) на Windows Server 2008 в дефолтной конфигурации компонент Report Services не будет доступен для установки.
Лечится это так — в настройке ролей сервера в разделе IIS добавить компоненты — IIS 6 Management Compatibility — Совместимость управления IIS 6.
Об этом описано в статье
MS KB 938245 — How to install and how to configure SQL Server 2005 Reporting Services on a computer that is running Windows Server 2008

Также дополнительную информацию по этому вопросу можно найти в стаптье из SQL Server 2005 Books Online (November 2008) — How to: Install and Configure Reporting Services on Windows Server 2008

После обновления роли IIS перезагружаем сервер. После ребута установка Report Services станет доступной.

После установки SQL Server 2005 отказывается стартовать служба полнотекстового поиска — SQL Server FullText Search


После установки SQL Server 2005 отказывается стартовать служба полнотекстового поиска — SQL Server FullText Search и в журнале System при старте этой службы регистрируется ошибка с кодом Event ID 7003 (источник — Service Control Manager Eventlog Provider)
и содержанием:

The SQL Server FullText Search (MSSQLSERVER) service depends the following service: NTLMSSP. This service might not be installed.

Проблема имеет два решения:

1) В системном реестре отключить зависимость от службы NTLMSSP: Найти в системном реестре ключ HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesmsftesqlDependOnService
Удалить из значения ключа параметр «NTLMSSP» и перезагрузить сервер.

2) Более простое и правильное — после установки SQL Server 2005 установить c WSUS пакет исправлений SP2 (или более новый).

После установки SP3 для SQL server 2005 cлужба SQL Server Reporting Services не стартует с описанием ошибки об истечении таймаута запуска

Замечено что после установки SP3 на SQL Server 2005 может перестать автоматически стартовать служба SQL Server Reporting Services, а при попытке стартовать службу вручную мы получим ошибку с описанием типа «Error 1053: The Service did not respond to start or control request in a timely fashion«.

В данном случае проблема может заключаться в том, что службе не хватает времени, отведенного системой на ответ от службы о том, что она выполнила запуск (по умолчанию это значение составляет 30 секунд). Для решения этой проблемы предлагается увеличить значение установленное по умочанию как минимум вдвое:

В системном реестре находим ветку  HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControl
Создаем в ней параметр DWORD с именем ServicesPipeTimeout и значением 60000 (Десятичное значение)
Перезагружаем компьютер и убеждаемся в то что проблемная служба успешно стартовала.

Обращаю ваше внимание на то что значение параметра указывается в миллисекундах и влияет на запуск всех служб в ОС.
Источник: Microsoft KB824344 How to debug Windows services

После установки SP3 на SQL Server может потеряться доступность вэбузла SQL 2005 Reporting Service

Данная проблема связана с тем что при установке SP3 на SQL Server 2005 в свойствах вэб узла SQL 2005 Reporting Service слетают настройки безопасности.
Для решения проблемы в консоли Internet Information Services (IIS) Manager раскроем Default Web Site и в нем найдем ReportServer. Выберем Handler Mappings.

image

Выбираем справа Edit Feature permissions и включаем права на Script и Execute.

image

This article uses a specific MS SQL 2005 Service Pack 4 installation error as an example, but may help in troubleshooting other Microsoft and Windows Update problems.

Installation of SQL server 2005 Service Pack 4 fails and Event ID 20 Error is recorded in Windows System Logs:

Type: Error
Event ID: 20
Description:
Installation Failure: Windows failed to install the following update with error 0x80070643: Microsoft SQL Server 2005 Service Pack 4 (KB2463332).
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.

This error is not specific to SQL 2005 SP4 and is just a generic code telling that an error was encountered by Windows Installer.
To get more specific code download offline Service Pack or Hotfix installation file from Microsoft. Just search MS download centre for KBxxxxxxx as displayed in Event ID 20 error. In case of SQL 2005 SP4 it is KB2463332.

Try installing your update running downloaded .exe or .msi. It will probably fail again, but this time you should be able to find more specific info in Windows Application Logs.
In case of SQL 2005 SP4 it can be something like this:

Type: Error
Event ID: 1023
Description:

Product: Microsoft SQL Server 2005 — Update ‘Service Pack 4 for SQL Server Database Services 2005 ENU (KB2463332)’ could not be installed. Error code 1603. Additional information is available in the log file C:Program FilesMicrosoft SQL Server90Setup BootstrapLOGHotfixSQL9_Hotfix_KB2463332_sqlrun_sql.msp.log.

Again, this is quite generic error, however this times it gives a path to a setup log file which will have much more information. Open the file in a text editor. Don’t get puzzled by the amount of information. Just search for «return value 3» and examine text just above this string. One of the lines should have a specific error which caused setup to fail. Going back to our SQL example third line above «return value 3» is:
FTECa.DLL: ERROR: FTE: InstallFTERef: Fail to create FTERef file: C:SQLMSSQL.1MSSQLFTDatanoiseCHS.txt, Err=3
In this case installation failed because path C:SQLMSSQL.1MSSQLFTData did not exist. Simply recreating missing folder fixes the problem. Obviously in your case error may be different.


Windows Server 2003
SQL 2005

Понравилась статья? Поделить с друзьями:
  • Sql 2003 error
  • Sql error 42883 error could not identify an equality operator for type json
  • Sql 1396 error
  • Sql error 42803 error aggregate functions are not allowed in group by
  • Sql 104 ошибка