SQL Server query optimization for stored procedure - sql-server

I need to improve the performance ofa stored procedure in SQL Server 2014.
Here is my procedure and I want optimise this procedure because this running to slowly.
Can anybody explain with some examples, which kind of query is better over what and in what situation?
CREATE PROCEDURE [dbo].[sp_Customer_SendMoney]
#CustomerId bigint,
#MobileNo nvarchar(15),
#Amount money,
#Comment nvarchar(250),
#PassPhrase nvarchar(50),
#Type varchar(50) = null
AS
BEGIN
DECLARE #returnCode INT
DECLARE #RetVal BIGINT, #CustomerBalance MONEY,
#CustomerMoneyRequestedId BIGINT,
#ToCustomerId BIGINT = 0,
#TransactionId BIGINT, #CustomerAccount BIGINT,
#FromCustomerBalance MONEY = 0,
#ToCustomerBalance MONEY = 0
IF EXISTS (SELECT Id FROM Customer
WHERE Id = #CustomerId AND IsDeleted = 0 AND IsActive = 1)
BEGIN
SELECT
#CustomerBalance = Balance
FROM
Customer
WHERE
Id = #CustomerId AND IsDeleted = 0 AND IsActive = 1
select #ToCustomerId = Id, #CustomerAccount = AccountNo,#ToCustomerBalance=Balance From Customer where convert(nvarchar,DecryptByPassPhrase(#PassPhrase, MobileNo)) = #MobileNo and IsDeleted = 0 and IsActive = 1
if(#ToCustomerId > 0)
begin
if( lower(isnull(#Type,'regular')) <> 'suspention')
begin
set #ToCustomerBalance=#ToCustomerBalance+#Amount
end
END
set #FromCustomerBalance=#CustomerBalance-#Amount
if((#CustomerBalance > 0) and (#CustomerBalance >= #Amount) )
Begin
BEGIN TRAN TxnsenMoney
BEGIN TRY
select #TransactionId = TransactionW2W+1 from MstGenerateTransactionID
where [year]=datepart(yyyy,getdate()) and [month]=DATENAME(month,getdate())
update MstGenerateTransactionID set TransactionW2W= #TransactionId
where [year]=datepart(yyyy,getdate()) and [month]=DATENAME(month,getdate())
--set #TransactionId = CONVERT(bigint,replace(convert(varchar, getdate(),111),'/','') + replace(convert(varchar, getdate(),114),':',''))
IF(#ToCustomerId > 0)
BEGIN
--Update sender Customer
update Customer set Balance = Balance - #Amount where Id = #CustomerId
--Update receiver Customer
if(lower(isnull(#Type,'regular')) <> 'suspention')
begin
update Customer set Balance = Balance + #Amount where Id = #ToCustomerId
end
else
begin
update Customer set SuspentionAccount = isnull(SuspentionAccount,0) + #Amount where Id = #ToCustomerId
end
INSERT INTO [TransactionW2W]
([TransactionId]
,[FromCustomerId]
,[ToCustomerId]
,[MobileNo]
,[Amount]
,[Comments]
,[CreatedOn]
,[FromCustomerBalance]
,[ToCustomerBalance])
VALUES
(#TransactionId
,#CustomerId
,#ToCustomerId
,#MobileNo
,#Amount
,#Comment
,GETDATE()
,#FromCustomerBalance
,#ToCustomerBalance)
End --end IF #ToCustomerId > 0
ELSE
BEGIN
--Update sender Customer
update Customer set Balance = Balance - #Amount where Id = #CustomerId
--print 'ELSE'
INSERT INTO [TransactionW2W]
([TransactionId]
,[FromCustomerId]
,[ToCustomerId]
,[MobileNo]
,[Amount]
,[Comments]
,[CreatedOn]
,[FromCustomerBalance])
VALUES
(#TransactionId
,#CustomerId
,#ToCustomerId
,#MobileNo
,#Amount
,#Comment
,GETDATE()
,#FromCustomerBalance)
INSERT INTO [NewCustomer]
([FromCustomerId]
,[MobileNo]
,[Amount]
,[CreatedOn]
)
VALUES
(#CustomerId
,#MobileNo
,#Amount
,GETDATE()
)
END --end ELSE #ToCustomerId > 0
print #RetVal
IF(##TRANCOUNT >0 )
begin
set #RetVal = #TransactionId
print #RetVal
end
else
begin
RAISERROR('records not executed',16,1)
END
COMMIT TRAN TxnsenMoney
END TRY
BEGIN CATCH
ROLLBACK TRAN TxnsenMoney
set #RetVal = -1
declare #error varchar(max)
set #error= ERROR_MESSAGE()
-- RAISERROR(#error,16,1)
print #error
END CATCH
select #RetVal
End
END
End

CREATE PROCEDURE [dbo].[sp_Customer_SendMoney]
#CustomerId bigint,
#MobileNo nvarchar(15),
#Amount money,
#Comment nvarchar(250),
#PassPhrase nvarchar(50),
#Type varchar(50) = null
AS
Begin
DECLARE #returnCode INT ,#RetVal bigint,#CustomerBalance money, #CustomerMoneyRequestedId bigint,#ToCustomerId bigint = 0,#TransactionId bigint,#CustomerAccount bigint,
#FromCustomerBalance money=0,#ToCustomerBalance money=0
IF EXISTS (select Id from Customer WITH(NOLOCK) where Id = #CustomerId and IsDeleted = 0 and IsActive = 1) Begin
select #CustomerBalance = Balance from Customer WITH(NOLOCK) where Id = #CustomerId and IsDeleted = 0 and IsActive = 1
select #ToCustomerId = Id, #CustomerAccount = AccountNo,#ToCustomerBalance=Balance From Customer WITH(NOLOCK)
where convert(nvarchar,DecryptByPassPhrase(#PassPhrase, MobileNo)) = #MobileNo and IsDeleted = 0 and IsActive = 1
IF(#ToCustomerId > 0)
BEGIN
if( lower(isnull(#Type,'regular')) <> 'suspention')
BEGIN
SET #ToCustomerBalance=#ToCustomerBalance+#Amount
END
END
SET #FromCustomerBalance=#CustomerBalance-#Amount
if((#CustomerBalance > 0) and (#CustomerBalance >= #Amount) )
Begin
BEGIN TRAN TxnsenMoney
BEGIN TRY
SELECT #TransactionId = TransactionW2W+1
FROM MstGenerateTransactionID WITH(NOLOCK)
WHERE [year]=datepart(yyyy,getdate()) and [month]=DATENAME(month,getdate())
update MstGenerateTransactionID set TransactionW2W= #TransactionId
where [year]=YEAR(GETDATE()) and [month]= MONTH(GETDATE())
--set #TransactionId = CONVERT(bigint,replace(convert(varchar, getdate(),111),'/','') + replace(convert(varchar, getdate(),114),':',''))
IF(#ToCustomerId > 0) BEGIN
--Update sender Customer
UPDATE Customer set Balance = Balance - #Amount where Id = #CustomerId
--Update receiver Customer
if(lower(isnull(#Type,'regular')) <> 'suspention') BEGIN
UPDATE Customer set Balance = Balance + #Amount where Id = #ToCustomerId
END ELSE BEGIN
UPDATE Customer set SuspentionAccount = isnull(SuspentionAccount,0) + #Amount where Id = #ToCustomerId
END
INSERT INTO [TransactionW2W]
([TransactionId] ,[FromCustomerId],[ToCustomerId] ,[MobileNo] ,[Amount],[Comments],[CreatedOn],[FromCustomerBalance],[ToCustomerBalance])
SELECT #TransactionId ,#CustomerId ,#ToCustomerId ,#MobileNo ,#Amount ,#Comment,GETDATE(),#FromCustomerBalance ,#ToCustomerBalance
END --end IF #ToCustomerId > 0
ELSE BEGIN
--Update sender Customer
UPDATE Customer set Balance = Balance - #Amount where Id = #CustomerId
--print 'ELSE'
INSERT INTO [TransactionW2W]
([TransactionId] ,[FromCustomerId],[ToCustomerId] ,[MobileNo] ,[Amount] ,[Comments] ,[CreatedOn],[FromCustomerBalance])
SELECT #TransactionId ,#CustomerId ,#ToCustomerId ,#MobileNo ,#Amount ,#Comment ,GETDATE() ,#FromCustomerBalance
INSERT INTO [NewCustomer]
([FromCustomerId] ,[MobileNo] ,[Amount] ,[CreatedOn] )
SELECT #CustomerId,#MobileNo ,#Amount,GETDATE()
END --end ELSE #ToCustomerId > 0
print #RetVal
IF(##TRANCOUNT >0 )BEGIN
set #RetVal = #TransactionId
print #RetVal
END ELSE BEGIN
RAISERROR('records not executed',16,1)
END
COMMIT TRAN TxnsenMoney
END TRY
BEGIN CATCH
ROLLBACK TRAN TxnsenMoney
SET #RetVal = -1
DECLARE #error varchar(max)
SET #error= ERROR_MESSAGE()
-- RAISERROR(#error,16,1)
print #error
END CATCH
select #RetVal
End
END
End

Related

Using transaction in cursor with try..catch

I have a large stored procedure which utilises a cursor. I want to put each instance of the cursor processing into a transaction, with a try-catch on the one insert, which on failure would terminate that transaction, back any inserts it did and then move to the next cursor instance. However, I am struggling with structuring this.
An example of what it looks like in brief is below. Basically I am trying to structure the try-catch for the patient insert to rollback the transaction and go onto the next cursor value when the patient insert fails.
Thanks
ALTER procedure [dbo].[Import_Archive_Record]
#PatientNumber varchar(10),
#PracticeId int
as
begin
DECLARE csr1 CURSOR for
select PatientNumber from ArchiveFull.dbo.ArchiveMasters where imported = 0 and PracticeId =
#PracticeId and PatientNumber = #PatientNumber
open csr1
fetch next from csr1 into #PatNo
while ##FETCH_STATUS = 0
begin
insert into Member....
select #memberId = SCOPE_IDENTITY()
print 'new member ' + cast(#memberId as varchar(10))
--insert patient
BEGIN TRY
select #initials = PatientInitials ,#surname = PatientSurname ,#name = PatientFirstname,
#DateOfBirth = DOBStr,#PatientCentury = DOBCen
from ArchiveFull.dbo.ArchiveMasters
where ArchiveFull.dbo.ArchiveMasters.PatientNumber = #PatNo
and imported = 0
and PracticeId = #PracticeId
set #patientID = null
select #patientID = id from Patient
where Initials = #initials
and Surname = #surname
and Name = #name
and MemberId = #memberId
print 'patientid ' + cast(#patientID as varchar(10))
set #DOB = dbo.getVisitdate(#PatientCentury,#DateOfBirth)
if #patientID is null
begin
insert into Patient(Name, Surname,Initials,MemberId,PostalSuburb,PostalCity,PostalCode,PostBox,Gender, DateofBirth,IDNumber,DependentCode,RelationToMember,AlternativesRelation,EMailAddress,CellPhone,Title)
select PatientFirstname,PatientSurname, coalesce(PatientInitials,'.'),#memberId,PatientAddress1, PatientAddress2, PatientAddress3,PatientAddress4,Gender,#DOB,PatientIDNumber,1,1,0,PatientEmail, CellNumber,PatientTitle
from ArchiveFull.dbo.ArchiveMasters
where PatientNumber = #PatNo
and imported = 0
END TRY
BEGIN CATCH
END CATCH
select #patientID = SCOPE_IDENTITY()
print 'new patientid ' + cast(#patientID as varchar(10))
end
set #BranchId = (select top 1 id from Branch where practiceid = #practiceId and ModalityRooms like concat('%', #BranchCode,'%'))
set #visitId = null
select #visitId = id from Visit
where BookingNumber = #PatNo
and BranchId = #BranchId
if #visitId is null
begin
declare #visitDate datetime
declare #century int
declare #date int
declare #DoctorCode nvarchar (max)
declare #DoctorSurname nvarchar (max)
declare #wca bit
select #century = Century, #date = ExamDateStr, #DoctorCode = RefDocCode, #DoctorSurname = RefDoc, #wca=WCA
from ArchiveFull.dbo.ArchiveMasters
where ArchiveFull.dbo.ArchiveMasters.PatientNumber = #PatNo
and imported = 0
and PracticeId = #PracticeId
update testlist
set century = #century, examdate = #date
where patno = #PatNo
set #visitDate = isnull(dbo.getVisitdate(#century,#date),'19000101')
set #DoctorId = null
set #DoctorId = dbo.getDoctorIdRadmin(#DoctorCode,#practiceId)
insert into Visit(Date,EndMonth, EndYear,NewBorn,HospitalClaim,WCA,WorkersComp,RAF,RoadAccidentFund,Examined,Booking,BookingNumber,PatientId,Notes,PreAuthorise,PreAuthNumber,BranchId,DoctorId, Receipted, ArchiveId)
select #visitDate, MONTH(#visitDate), YEAR(#visitdate) ,0,0,0,'',0,'',1,1,#PatNo,#patientID,'',0,AUTHNO,#BranchId,#DoctorId, 0, #archiveid
from ArchiveFull.dbo.ArchiveMasters
where ArchiveFull.dbo.ArchiveMasters.PatientNumber = #PatNo
and imported = 0
and PracticeId = #PracticeId
fetch next from csr1 into #PatNo
end
close csr1
deallocate csr1

SQL Transactions - two inserts

I wrote a SQL procedure that inserts data into two tables. I started with begin transaction but some data violate constraint of second table and in the end data are added into first table, but not in second. What is wrong with my code?
create procedure [dbo].[procAddConference]
#Conf_name varchar(50),
#Begin_date date,
#End_date date,
#Price money,
#Student_disc numeric(3,2),
#Limit int,
#Disc numeric(3,2),
#Until int
as
set nocount on
begin transaction;
begin try
IF (#Begin_date > #End_date or #Limit < 0 or #Disc <0 or #Disc >1 or #Student_disc < 0 or #Student_disc > 1)
BEGIN
; throw 52000, 'Wrong data', 1
END
insert into Conferences (ConferenceName, BeginDate, EndDate, Price, StudentDiscount)
values (#Conf_name, #Begin_date, #End_date, #Price, #Student_disc)
IF ##ERROR <> 0
begin
RAISERROR('Error, transaction not completed!',16,-1)
rollback transaction;
end
declare #confID INT
set #confID = ##IDENTITY
declare #duration int
declare #iterator int
set #duration = DATEDIFF(dd, #Begin_date, #End_date)
set #iterator = 0
while #iterator <= #duration
begin
insert into ConferenceDay (ConferenceID, Date, Limit)
values (#confID, cast(DATEADD(dd, #iterator, #Begin_date) as date), #Limit)
IF ##ERROR <> 0 or ##ROWCOUNT = 0
begin
rollback transaction;
RAISERROR('Error, transaction not completed!',16,-1)
end
set #iterator = #iterator + 1
end
commit transaction;
END TRY
BEGIN CATCH
DECLARE #errorMsg nvarchar (2048) = 'Cannot add conference . Error message : ' + ERROR_MESSAGE () ;
; THROW 52000 , #errorMsg ,1
rollback transaction;
END CATCH
END

Insert/Update Stored Procedure with Output Parameter

Background:
I have a series of stored procedures that inserts one new record into 5 tables (all have a one-to-one relationship). Each stored procedure creates a unique ID for the related table. The last stored procedure adds all of those unique IDs into the last table (to allow for an INNER JOIN to retrieve all information across the individual tables).
I have created an additional stored procedure (let's call it spWrapper) that calls the 4 individual stored procedures (mentioned above). I would like to use the spWrapper to both insert and update a record. The current (insert) spWrapper only inserts a record; the 5 unique IDs are declared as OUTPUT parameters. My T-SQL knowledge is still basic and I am not sure how OUTPUT parameters affect stored procedures.
The current spWrapper code (shortened example):
ALTER PROCEDURE [dbo].[spWrapper]
-- Return values
#idAddress INT = NULL OUTPUT,
#idDetermination INT = NULL OUTPUT,
#idLegalDescription INT = NULL OUTPUT,
#idAddresses_LegalDescriptions_Determinations INT = NULL OUTPUT,
#idLOMC INT = NULL OUTPUT,
-- [Table#1] parameters
#Street VARCHAR(50) = NULL,
#City VARCHAR(50) = NULL,
#State VARCHAR(2) = NULL,
#ZipCode5 VARCHAR(5) = NULL,
#ZipCode4 VARCHAR(4) = NULL,
#GISCode VARCHAR(15) = NULL
AS
SET NOCOUNT OFF
SET ROWCOUNT 0
-- =================================
-- Declare and initialize variables
-- =================================
DECLARE #Error INT,
#RC INT,
#Trancount INT,
#Message VARCHAR(255)
SELECT #Error = 0,
#RC = 0,
#Trancount = ##TRANCOUNT,
#Message = NULL
-- ==========================================
-- Insert record into [Table#1]
-- ==========================================
IF #idAddress IS NULL
BEGIN
IF #Trancount = 0 BEGIN TRANSACTION
EXEC #RC = [spTable#1]
#idLogin = #idLogin,
#idAddress = #idAddress,
#Street = #Street,
#State = #State,
#City = #City,
#ZipCode5 = #ZipCode5,
#ZipCode4 = #ZipCode4,
#GISCode = #GISCode
SELECT #Error = ##ERROR
IF #RC <> 0 OR #Error <> 0
BEGIN
IF #Trancount = 0 ROLLBACK TRANSACTION
SELECT #Message = 'dbo.spWrapper: Error inserting record into [Table#1]'
GOTO lbl_abort
END
END
IF #Trancount = 0 COMMIT TRANSACTION
The current spTable#1 code
ALTER PROCEDURE [spTable#1]
#idLogin INT,
#idAddress INT = NULL OUTPUT,
#Street VARCHAR(50),
#State CHAR(2),
#City VARCHAR(50),
#ZipCode5 CHAR(5),
#ZipCode4 CHAR(4),
#GisCode VARCHAR(15)
IF #TranCount = 0 BEGIN TRANSACTION
IF #idAddress IS NULL
BEGIN
INSERT [dbo].[Table#1]
(Street,
[State],
City,
ZipCode5,
ZipCode4,
GisCode,
InsertedidLogin,
InsertedDate)
VALUES
(#Street,
#State,
#City,
#ZipCode5,
#ZipCode4,
#GisCode,
#idLogin,
GETDATE())
SELECT #Error = ##ERROR,
#RC = ##ROWCOUNT,
#idAddress = SCOPE_IDENTITY()
IF #Error <> 0 OR #RC <> 1
BEGIN
IF #TranCount = 0 ROLLBACK TRANSACTION
SELECT #Message = 'spTable#1: Error inserting record into [Table#1]'
GOTO lbl_abort
END
END
My main question:
With the unique ID set as an OUTPUT parameter, can I insert an existing ID to call an UPDATE portion of spTable#1 (and subsequently spWrapper)? OR can I declare those unique IDs (ie: not as an OUTPUT parameter)?
Proposed change
CREATE PROCEDURE [dbo].[spWrapper]
#idLOMC INT = NULL
DECLARE #idAddress INT,
#idLegalDescription INT,
#idDetermination INT,
#idCommunity INT,
#idFirm INT,
#idCounty INT,
#idFloodZone INT,
#Error INT,
#RC INT,
#Trancount INT,
#Message VARCHAR(255)
SELECT #idAddress = NULL,
#idLegalDescription = NULL,
#idDetermination = NULL,
#Error = 0,
#RC = 0,
#Trancount = ##TRANCOUNT,
#Message = NULL
/* Lookup idAddress, idLegalDescription, idDetermination */
IF #idLOMC IS NOT NULL
BEGIN
SELECT #idAddress = A.idAddress, #idLegalDescription = LD.idLegalDescription, #idDetermination = D.idDetermination
FROM [Table#2] L
INNER JOIN [Table#5] ALD
ON L.idAddresses_LegalDescriptions_Determinations = ALD.idAddresses_LegalDescriptions_Determinations
INNER JOIN [Table#1] A
ON ALD.idAddress = A.idAddress
INNER JOIN [Table#3] LD
ON ALD.idLegalDescription = LD.idLegalDescription
INNER JOIN [Table#4] D
ON ALD.idDetermination = D.idDetermination
WHERE L.idLOMC = #idLOMC
IF ##ROWCOUNT = 0
BEGIN
SELECT #Message = 'dbo.spWrapper: Invalid idLOMC'
GOTO lbl_abort
END
END
/* Insert record into [Table#1] */
IF #idAddress IS NULL
BEGIN
IF #Trancount = 0 BEGIN TRANSACTION
EXEC #RC = [spTable#1]
#idLogin = #idLogin,
#idAddress = #idAddress OUTPUT,
#Street = #Street,
#State = #State,
#City = #City,
#ZipCode5 = #ZipCode5,
#ZipCode4 = #ZipCode4,
#GisCode = #GisCode
SELECT #Error = ##ERROR
IF #RC <> 0 OR #Error <> 0
BEGIN
IF #Trancount = 0 ROLLBACK TRANSACTION
SELECT #Message = 'spWrapper: Error inserting record into [Table#1]'
GOTO lbl_abort
END
END
/* Update record into [Table#1] */
ELSE
BEGIN
IF #Trancount = 0 BEGIN TRANSACTION
EXEC #RC = [spTable#1]
#idLogin = #idLogin,
#idAddress = #idAddress,
#Street = #Street,
#State = #State,
#City = #City,
#ZipCode5 = #ZipCode5,
#ZipCode4 = #ZipCode4,
#GisCode = #GisCode
SELECT #Error = ##ERROR
IF #RC <> 0 OR #Error <> 0
BEGIN
IF #Trancount = 0 ROLLBACK TRANSACTION
SELECT #Message = 'spWrapper: Error updating record in [TspTable#1]'
GOTO lbl_abort
END
END

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT - Stored Procedure?

I am getting this exception about commits but am not sure what exactly is wrong with my Stored Procedure. I have read answers in other questions but am unable to find where exactly the commit count is getting messed up.
Herewith the Stored Procedure I use:
USE [AFS_GROUP]
GO
/****** Object: StoredProcedure [dbo].[SBO_SP_TransactionNotification] Script Date: 12/12/2012 10:41:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[SBO_SP_TransactionNotification]
#object_type nvarchar(20), -- SBO Object Type
#transaction_type nchar(1), -- [A]dd, [U]pdate, [D]elete, [C]ancel, C[L]ose
#num_of_cols_in_key int,
#list_of_key_cols_tab_del nvarchar(255),
#list_of_cols_val_tab_del nvarchar(255)
AS
begin
-- Return values
declare #error int -- Result (0 for no error)
declare #error_message nvarchar (200) -- Error string to be displayed
select #error = 0
select #error_message = N'Ok'
IF #object_type = 13 AND #transaction_type = 'A'
BEGIN
UPDATE INV1
SET U_jnl1='N', U_jnl2='N', U_jnl3='N', U_jnl4='N'
WHERE DocEntry = #list_of_cols_val_tab_del
DECLARE #CallIDo13 VARCHAR(10) = (SELECT TOP 1 [U_HEATID] FROM OINV WHERE [DocEntry] = #list_of_cols_val_tab_del);
DECLARE #DocNumo13 VARCHAR(MAX) = (SELECT TOP 1 [DocNum] FROM OINV WHERE [DocEntry] = #list_of_cols_val_tab_del);
EXEC [AFSJHBSQL01].[HEAT].[dbo].[uspCreateJournalFromINV] #CallIDo13, #DocNumo13, #object_type;
END
ELSE IF #object_type = 14 AND #transaction_type = 'A'
BEGIN
UPDATE RIN1
SET U_jnl1='N', U_jnl2='N', U_jnl3='N', U_jnl4='N'
WHERE DocEntry = #list_of_cols_val_tab_del
END
ELSE IF #object_type = 15 AND #transaction_type = 'A'
BEGIN
UPDATE DLN1
SET U_jnl1='N', U_jnl2='N', U_jnl3='N', U_jnl4='N'
WHERE DocEntry = #list_of_cols_val_tab_del
DECLARE #CallIDo15 VARCHAR(10) = (SELECT TOP 1 [U_HEATID] FROM ODLN WHERE DocEntry = #list_of_cols_val_tab_del);
DECLARE #DocNumo15 VARCHAR(MAX) = (SELECT TOP 1 [DocNum] FROM ODLN WHERE DocEntry = #list_of_cols_val_tab_del);
EXEC [AFSJHBSQL01].[HEAT].[dbo].[uspCreateJournalFromDN] #CallIDo15, #DocNumo15, #object_type;
END
ELSE IF #object_type = 16 AND #transaction_type = 'A'
BEGIN
UPDATE RDN1
SET U_jnl1='N', U_jnl2='N', U_jnl3='N', U_jnl4='N'
WHERE DocEntry = #list_of_cols_val_tab_del
END
ELSE IF #object_type = 17 AND #transaction_type = 'A'
BEGIN
DECLARE #ItemCode VARCHAR(MAX) = (SELECT TOP 1 [ItemCode] FROM [RDR1] WHERE [DocEntry] = #list_of_cols_val_tab_del AND ([ItemCode] = 'VIU Chip Prod' OR [ItemCode] = 'FPR Chip Production'));
DECLARE #Desc VARCHAR(MAX) = (SELECT TOP 1 [CardName] FROM ORDR WHERE [DocEntry] = #list_of_cols_val_tab_del);
--DECLARE #CallID VARCHAR(10) = (SELECT TOP 1 [U_HEATID] FROM ORDR WHERE [DocEntry] = #list_of_cols_val_tab_del);
IF (#ItemCode = 'VIU Chip Prod')
BEGIN
EXEC [AFSJHBSQL01].[HEAT].[dbo].[uspCreateHeatJobFromSO] #list_of_cols_val_tab_del, #ItemCode, #Desc;
--RETURN;
END
ELSE IF(#ItemCode = 'FPR Chip Production')
BEGIN
EXEC [AFSJHBSQL01].[HEAT].[dbo].[uspCreateHeatJobFromSO] #list_of_cols_val_tab_del, #ItemCode, #Desc;
--RETURN;
END
END
--------------------------------------------------------------------------------------------------------------------------------
-- Select the return values
select #error, #error_message
END

SQL nested IF's not working

From the looks of it I've wrapped everything in the proper BEGIN...END statements, however the code goes through and executes almost every single line of code. I've done print statements too to make sure that both #rows variables actually do contain values greater than 0. Can anyone help point me in the right direction?
IF #rows > '0'
--This agent's Tax ID number has been found to exist in AgentIdentification table
BEGIN
--Set UniqueAgentId according to mapped value from AgentIdentification table
SELECT #uniqueAgentId = UniqueAgentId
FROM AgentIdentification
WHERE AgentTaxId = #ssn
--Check to make sure this record exists in UniqueAgentIdToAgentId table
SELECT #rows = COUNT(*)
FROM UniqueAgentIdToAgentId
WHERE UniqueAgentId = #uniqueAgentId and AgentId = #agentId
PRINT #rows
IF #rows > 0
--Record exists in UniqueAgentIdToAgentId table
--Check to make sure correct UniqueAgentId is mapped to correct AgentId and vice versa
BEGIN
SELECT #agentIdRows = COUNT(AgentId)
FROM UniqueAgentIdToAgentId
WHERE UniqueAgentId = #uniqueAgentId and AgentId <> #agentId
SELECT #uniqueIdRows = COUNT(UniqueAgentId)
FROM UniqueAgentIdToAgentId
WHERE AgentId = #agentId and UniqueAgentId <> #uniqueAgentId
IF #uniqueIdRows = 0 AND #agentIdRows = 0
BEGIN
SET #returnValue = 1
END
ELSE IF #agentIdRows = 0 AND #uniqueIdRows > 0
BEGIN
SET #returnValue = 2
END
ELSE
BEGIN
SET #returnValue = 3
END
END
--Record does not exist in UniqueAgentIdToAgentId and will be added
ELSE
BEGIN
INSERT INTO UniqueAgentIdToAgentId (UniqueAgentId, AgentId, CompanyCode, LastChangeOperator, LastChangeDate)
VALUES (#uniqueAgentId, #agentId, #companyCode, #lastChangeOperator, #LastChangeDate)
SET #returnValue = 4
END
END
ELSE
BEGIN TRANSACTION
--This agent Tax ID number does not exist on AgentIdentification table
--Add record into Agent and AgentIdentification table
INSERT INTO Agent (EntityType, FirstName, LastName, NameSuffix, CorporateName, LastChangeOperator, LastChangeDate)
VALUES (#entityType, #firstName, #lastname, '', #corporateName, #lastChangeOperator, #LastChangeDate)
SELECT #uniqueAgentId = ##IDENTITY
SELECT UniqueAgentId
FROM Agent
INSERT INTO AgentIdentification (UniqueAgentId, TaxIdType, AgentTaxId, LastChangeOperator, LastChangeDate)
VALUES (#uniqueAgentId, #taxIdType, #ssn, #lastChangeOperator, #lastChangeDate)
--Check to make sure this record exists in UniqueAgentIdToAgentId table
SELECT #rows = COUNT(*)
FROM UniqueAgentIdToAgentId
WHERE UniqueAgentId = #uniqueAgentId and AgentId = #agentId
IF #rows > 0
--Record exists in UniqueAgentIdToAgentId table
--Check to make sure correct UniqueAgentId is mapped to correct AgentId and vice versa
BEGIN
SELECT #agentIdRows = COUNT(AgentId)
FROM UniqueAgentIdToAgentId
WHERE UniqueAgentId = #uniqueAgentId and AgentId <> #agentId
SELECT #uniqueIdRows = COUNT(UniqueAgentId)
FROM UniqueAgentIdToAgentId
WHERE AgentId = #agentId and UniqueAgentId <> #uniqueAgentId
IF #uniqueIdRows = 0 AND #agentIdRows = 0
BEGIN
SET #returnValue = 5
END
ELSE IF #agentIdRows = 0 AND #uniqueIdRows > 0
BEGIN
SET #returnValue = 6
END
ELSE
BEGIN
SET #returnValue = 7
END
END
--Record does not exist in UniqueAgentIdToAgentId and will be added
ELSE
BEGIN
INSERT INTO UniqueAgentIdToAgentId (UniqueAgentId, AgentId, CompanyCode, LastChangeOperator, LastChangeDate)
VALUES (#uniqueAgentId, #agentId, #companyCode, #lastChangeOperator, #LastChangeDate)
SET #returnValue = 8
END
COMMIT TRANSACTION
I think this:
ELSE
BEGIN TRANSACTION
Needs to be this:
ELSE
BEGIN
BEGIN TRANSACTION
And this:
COMMIT TRANSACTION
Needs to be this:
COMMIT TRANSACTION
END

Resources