error

1. Error Handling

1.1 What is Error Handling?

  • Concept of dealing with Errors BEFORE they happen
  • Preventative
    maintenance
  • No one way to perform Error Handling
  • Better to prevent than deal with issues (use trigger

1.2 Methods of Error Handling

1.2.1 RaisError

It is s system function for providing info about the error. RAISERROR takes min of 3 parameter and it can be more based on error message requirements
Param1: msg_id from sys.messages or user defined message string or a variable which has error message or error id
Param2: Severity or Level. User can define his own severity level or if -1 is used severity is same as from sys.messages
Param3: State values range from 0-255
Other Params are based in error message requirements

  • Create Custom Errors
  • Levels
    0-10 Warning
    11-18 Critical
    19-24 System Critical (by system,can not created by ourself )

like raise a flag

1.2.2 @@Error

  • Retrieve the error message number for last statement run
  • Provides error number for the most recent error if @@ERROR is followed by that statement.
    Ex: SELECT 1/0; SELECT @@ERROR
  • It gives only error number
  • If there is any statement in between errored SQL statement and @@ERROR, @@ERROR will not be able to show the error number (it shows 0)
  • It will only show the number but cannot provide functionality for alternate process as it is a global variable (system function)

1.2.3Try….Catch

  • Allows to monitor for error, if error then execute Catch, Else continue

  • try block where you write your code you want to execute

  • catch block where you want will write code to handel errors,if there is any error in any line or try block execution immediately moves to catch block, it will not continue execute any other statement within the try block

  • can be nested, no limited number

  • some function only can used in catch block:
    error_message(),error_number(),error_procedure(),error_severity() 等级

如果catch错了,再创建一个catch block

1.2.4 If…Else

Mainly for logical use, one can anticipate possible errors and make proper conditions

1.2.5 throw

THROW: It is a new error function provided from SS 2012. It takes 3 parameters.
Param1: Message ID that user wants to display for the message
Param2: Message text
Param3: State
Severity is always 16 unless THROW is displaying original system message and severity.
THORW will give original exception in CATCH block.
THROW needs previous statement to be terminated with a semi colon.

  • use in catch log: give your original system erroronly way give your system error
  
CREATE TABLE dbo.TestRethrow  
(    ID INT PRIMARY KEY  
);  
BEGIN TRY  
    INSERT dbo.TestRethrow(ID) VALUES(1);  
--  Force error 2627, Violation of PRIMARY KEY constraint to be raised.  
    INSERT dbo.TestRethrow(ID) VALUES(1);  
END TRY  
BEGIN CATCH  
  
    PRINT 'In catch block.';  
    THROW;  
END CATCH;  

differencr between raiseerror and throw

  • throw will stop procedure, raiseerror will keep
  • throw give the real level number
  • throw can use greater 51000 ,error will not give
    difference

    https://docs.microsoft.com/en-us/sql/t-sql/language-elements/throw-transact-sql?view=sql-server-2017

14.3 视频代码

---syntax is correct
begin try
    select BusinessEntityID+JobTitle
    from AdventureWorks2017.HumanResources.Employee
end try

begin catch
    Print   'please corrext your syntax'
end catch



go
begin try
    select BusinessEntityID+JobTitle
    from AdventureWorks2017.HumanResources.Employee
end try

begin catch
    raiserror('there has been an error',5,2)
end catch
------------------create critical level
go
begin try
    select BusinessEntityID+JobTitle
    from AdventureWorks2017.HumanResources.Employee
end try

begin catch
    raiserror('there has been an error',13,2)  ---crtical level:13
end catch
-----------log: get the log file of error
go
begin try
    select BusinessEntityID+JobTitle
    from AdventureWorks2017.HumanResources.Employee
end try

begin catch
    raiserror('there has been an error',22,2)  ---crtical level
    with log
end catch


select BusinessEntityID+JobTitle
    from AdventureWorks2017.HumanResources.Employee
select @@error

select *
from sys.messages
where message_id =@@error

14.4 note

DROP TABLE IF EXISTS Person
GO
CREATE TABLE Person
(PerID INT IDENTITY PRIMARY KEY,
PerName VARCHAR(100) NOT NULL
)
GO

IF OBJECT_ID('PersonDep') IS NOT NULL
DROP TABLE PersonDep
GO

CREATE TABLE PersonDep
(
PerDepID INT IDENTITY (101,1) PRIMARY KEY,
DepName VARCHAR(100) NOT NULL,
DOB DATE CHECK (DATEDIFF(YY, DOB, GETDATE()) < 18),
PerID INT FOREIGN KEY REFERENCES Person(PerID) 
)
GO

CREATE OR ALTER PROC spPerDetails 
(@PerName VARCHAR(100), @DepName VARCHAR(100), @DepDOB DATE)
AS
    DECLARE @PerID INT = 0

    BEGIN TRY
        INSERT INTO Person VALUES
        (@PerName)
        --PRINT 'After Parent Insert'
        SET @PerID = (SELECT MAX(PerID)
                      FROM Person 
                      WHERE PerName = @PerName) 
        --PRINT 'After SET'
        INSERT INTO PersonDep VALUES
        (@DepName, @DepDOB, @PerID)
    END TRY

    BEGIN CATCH
        PRINT 'Invalid DATE is provided for DOB of Dependent'
        DELETE FROM Person
        WHERE PerID = @PerID
        EXEC spPerDetails @PerName, @DepName, NULL

    END CATCH
GO

EXEC spPerDetails 'Jason', 'Eva', '12/15/2016'

SELECT * FROM Person
SELECT * FROM PersonDep

EXEC spPerDetails 'Kaminsky', 'Viva', '12/15/2000'


你可能感兴趣的:(error)