@@ERROR
Returns an error number if the previous statement encountered an error. If the error was one of the errors in the sys.messages catalog view, then @@ERROR contains the value from the sys.messages.message_id column for that error. You can view the text associated with an @@ERROR error number in sys.messages.
Because @@ERROR is cleared and reset on each statement executed, check it immediately following the statement being verified, or save it to a local variable that can be checked later.
Simple Example;
CREATE TABLE [dbo].[tblTest](
[NAME] [varchar](100) NOT NULL,
CONSTRAINT [PK_tblTest_1]
PRIMARY KEY CLUSTERED
(
[NAME] ASC
)
)
GO
INSERT INTO tblTest
Select 'Atif'
Union
Select 'Sheikh'
Update tblTest
Set Name = 'Atif'
Where Name = 'Sheikh'
if @@ERROR <> 0
print 'Error Generated'
else
Print 'No Error.'
TRY CATCH
We can also make use of TRY CATCH block in order to catch the error;
BEGIN TRY
Update tblTest
Set Name = 'Atif'
Where Name = 'Sheikh'
END TRY
BEGIN CATCH
print 'Error Generated.'
END CATCH
BEGIN TRY
Update tblTest
Set Name = 'Atif'
Where Name = 'Sheikh'
END TRY
BEGIN CATCH
print 'Error Generated.'
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH
THROW
BEGIN TRY
Update tblTest
Set Name = 'Atif'
Where Name = 'Sheikh'
END TRY
BEGIN CATCH
print 'Error Generated.';
THROW;
END CATCH
BEGIN TRY
Update tblTest
Set Name = 'Atif'
Where Name = 'Sheikh'
END TRY
BEGIN CATCH
print 'Error Generated.';
THROW 51000, 'Primary Key Violates.',
1;
END CATCH
LOSYCO ist ein kompetentes, Handling spezialisiertes Unternehmen im Bereich der Produktions-Logistik. Konzipiert und realisiert werden Lean-Produktions-Systeme aus einer Hand.
ReplyDeleteVisit Now - http://losyco.com/landingpages/handling.html