Below is my code I am trying to develop and facing below error , please guide where am I wrong.
To get rid of Locks I am trying to use WITH (NOLOCK) clause , I cannot use it . Is this expected!
Msg 266, Level 16, State 2, Procedure uspMyProc, Line 0 [Batch Start Line 71]
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 119, current count = 158.
USE MyDB
go
ALTER PROCEDURE dbo.MyProc
(
@maxrow INT = 600000
,@batch INT = 20000
,@rows INT = 0
,@rowsdel INT = 1
) AS
WHILE @maxrow >= @rows and @rowsdel > 0
BEGIN TRY
SET DEADLOCK_PRIORITY LOW;
IF (EXISTS (SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'MyTable'))
WAITFOR DELAY '00:00:00:01'
SET IDENTITY_INSERT dbo.MyTablebkp ON
BEGIN TRAN
DELETE TOP(@batch) FROM dbo.MyTable --WITH (NOLOCK)
OUTPUT
DELETED.[Column1],DELETED.[Column2]
INTO dbo.MyTablebkp
(Column1,Column2)
--WHERE CONDITION MANDATORY
SET @rowsdel = @@ROWCOUNT
SET @rows += @rowsdel
IF @rows = @maxrow
BREAK
SET IDENTITY_INSERT dbo.MyTablebkp OFF
PRINT 'Looped :' + CONVERT (VARCHAR(10), @rows)
PRINT 'Per Batch :' + CONVERT (VARCHAR(10), @rowsdel)
END TRY
BEGIN CATCH
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
IF @@TRANCOUNT > 0
BEGIN
COMMIT TRAN
RETURN 0
END