Below is the code for my stored procedure but I am not completely clear with the flow of execution. How the @@RAISERROR() in my case will work and how it will change the normal flow? Also what does the number 10 & 1 mean in that function. There are few other numbers also that can be used instead of 10 & 1 so how all the number affects flow of execution. Please let me know if my coding structure of style is bad/wrong or if there is any scope for improvement.
Below is my code.
CREATE PROCEDURE spAddressMaster
@Mode varchar(20),
@Street varchar(MAX),
@City varchar(300),
@State varchar(300),
@Country varchar(300),
@PostalCode int,
@Remarks varchar(MAX),
@Type varchar(300)
AS
BEGIN
BEGIN TRANSACTION
BEGIN TRY
--INSERT MODE--
IF(@Mode='INSERT')
BEGIN
INSERT INTO [AddressMST] (
[Street],
[City],
[State],
[Country],
[PostalCode],
[Remarks],
[Type]
)
VALUES (
@Street,
@City,
@State,
@Country,
@PostalCode,
@Remarks,
@Type
)
IF(@@ERROR<>0)
RAISERROR('Insert Operation Fail',10,1)
END
END TRY
BEGIN CATCH
IF(@@ERROR<>0)
BEGIN
ROLLBACK TRANSACTION
SELECT ERROR_MESSAGE()
END
END CATCH
END
GO
First off, you have a big problem: you have a
BEGIN TRANSACTIONwithout anyCOMMIT. That’s about as wrong as you can get when programming for databases! Use this general structure:Next up, when you are executing code within a
BEGIN TRYblock, if any errors are raised execution is immediately transferrred to theBEGIN CATCHblock. This means that theIF(@@ERROR<>0)block will only ever be executed when no errors have occured, i.e. @@ERROR will always be 0.As for the meaning of the 10 and 1 in the RAISERROR, that is complex, detailed, and best explained in SQL Server books online under the entry “RAISERROR”. Here’s the Link.