CREATE PROCEDURE TEST ( @IncrStartDate DATE ,@IncrEndDate DATE ,@SourceRowCount INT OUTPUT ,@TargetRowCount INT OUTPUT ,@ErrorNumber INT OUTPUT ,@ErrorMessage VARCHAR(4000) OUTPUT ,@InsertCase INT --INSERT CASE INPUT ) WITH EXEC AS CALLER AS BEGIN --Main Begin SET NOCOUNT ON BEGIN TRY DECLARE @SuccessNumber INT = 0 ,@SuccessMessage VARCHAR(100) = 'SUCCESS' ,@BenchMarkLoadFlag CHAR(1) ,@BenchmarkFlow INT ,@MonthYearStart DATE ,@MonthYearEnd DATE ,@StartDate DATE ,@EndDate DATE /* Setting the default values of output parameters to 0.*/ SET @SourceRowCount = 0 SET @TargetRowCount = 0 /*Setting the Start and end date for looping */ SET @MonthYearStart = @IncrStartDate; SET @MonthYearEnd = @IncrEndDate; /* Setting the @InsertCase will ensure case wise insertion as this sp will load data in different tables @InsertCase =0 means data will be inserted in the target TAB1 @InsertCase =1 means data will be inserted in the target TAB2 @InsertCase =2 means data will be inserted in the target TAB3 @InsertCase =3 means data will be inserted in the target TAB4 @InsertCase =4 means data will be inserted in the target TAB5 @InsertCase =5 means data will be inserted in the target TAB6 */ if @InsertCase =0 WHILE (@MonthYearStart <= @MonthYearEnd) BEGIN SET @StartDate = @MonthYearStart; SET @EndDate = @MonthYearEnd; /* Delete from target where date range given from input parameter*/ DELETE FROM TAB1 WHERE [MONTH] BETWEEN MONTH(@StartDate) AND MONTH(@EndDate) AND [YEAR] BETWEEN year(@StartDate) and year(@EndDate) /*Insert data in target-TAB1 */ BEGIN TRANSACTION INSERT INTO TAB1 ( A,B,C ) SELECT A,BC FROM XYZ COMMIT TRANSACTION SET @MonthYearStart = DATEADD(MONTH, 1, @MonthYearStart) SELECT @TargetRowCount = @TargetRowCount + @@ROWCOUNT; END -- End of whileloop END TRY BEGIN CATCH IF @@TRANCOUNT>0 ROLLBACK TRANSACTION SELECT @ErrorNumber = ERROR_NUMBER() ,@ErrorMessage = ERROR_MESSAGE(); END CATCH END--End of Main Begin
I have the above proc inserting data based on parameters where in @InsertCase is used for case wise execution.
I have written the whole proc with exception handling using try catch block.
I have just added one insert statement here for 1 case now I need to add further insert cases
------
INSERT INTO TAB4
(
A,B,C
)
SELECT
A,BC
FROM XYZ
------
INSERT INTO TAB3
(
A,B,C
)
SELECT
A,BC
FROM XYZ
INSERT INTO TAB2
(
A,B,C
)
SELECT
A,BC
FROM XYZ
-------
I will be using following to insert further insert statements
if @InsertCase =1
I just needed to know where will be my next insert statement should be fitting int his code so that i cover exception handling for all the code
Mudassar