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
Related
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
I have an issue with the procedure below.
Error is:
Msg 402, Level 16, State 1, Procedure Get_FormattedBankStatement, Line
87. The data types nvarchar and nvarchar are incompatible in the subtract operator.
USE [K2_Objects]
GO
/****** Object: StoredProcedure [K2RestSrv].[Get_FormattedBankStatement] Script Date: 2/27/2019 5:00:12 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [K2RestSrv].[Get_FormattedBankStatement]
--Declaring input parameter variable
#OpeningBalance Decimal(18,2),
#jsonValue nvarchar(max)
AS
BEGIN
DECLARE
#TotalCount nvarchar(150),
#MinRowNum int, #MaxRowNum int,
#DebitRecord nvarchar(150),
#CreditRecord nvarchar(150),
#NewBalance nvarchar(150),
#PreviousBalance nvarchar(150);
--Creating Temp Table #GetRowID
Create table #GetStatement
(ID int identity(1,1),
PostDate nvarchar(150),
TransDate nvarchar(150),
ValueDate nvarchar(150),
TransID nvarchar(150),
Narration nvarchar(max),
Debit nvarchar(150),
Credit nvarchar(150),
Balance nvarchar(150));
--Inserting into TempTable #GetStatement Temp Table, from the select statement
INSERT INTO #GetStatement
(PostDate,
TransDate,
ValueDate,
TransID,
Narration,
Debit,
Credit,
Balance)
SELECT
max(case when name='post_date' then convert(nvarchar(150),StringValue) else '' end) as [PostDate],
max(case when name='tran_date' then convert(nvarchar(150),StringValue) else '' end) as [TranDate],
max(case when name='value_date' then convert(nvarchar(150),StringValue) else '' end) as [ValueDate],
max(case when name='tran_id' then convert(nvarchar(150),StringValue) else '' end) as [TransID],
max(case when name='narration' then convert(nvarchar(150),StringValue) else '' end) as [Narration],
max(case when name='debit' then convert(nvarchar(150),StringValue) else '' end) as [Debit],
max(case when name='credit' then convert(nvarchar(150),StringValue) else '' end) as [Credit],
max(case when name='balance' then convert(nvarchar(150),StringValue) else '' end) as [Balance]
FROM parseJSON
(
#jsonValue
)
WHERE ValueType IN ('string','real','int','object','array') and Object_ID is NULL
GROUP BY parent_ID;
--Selecting the first and Last RowNum from the TempTable
SET #MinRowNum = (SELECT Min(ID) FROM #GetStatement)
SET #MaxRowNum = (SELECT Max(ID) FROM #GetStatement)
SET #PreviousBalance = #OpeningBalance;
WHILE #MinRowNum < #MaxRowNum
BEGIN
SET #DebitRecord = (SELECT Debit FROM #GetStatement WHERE ID = #MinRowNum);
SET #CreditRecord = (SELECT Credit FROM #GetStatement WHERE ID = #MinRowNum);
SET #NewBalance = (#PreviousBalance - (#DebitRecord + #CreditRecord));
UPDATE #GetStatement SET Balance = #NewBalance WHERE ID = #MinRowNum;
SET #PreviousBalance = (Select Balance from #GetStatement where ID = #MinRowNum);
SET #MinRowNum = (#MinRowNum + 1);
END
Select ID, PostDate,TransDate,ValueDate,TransID,Narration,Debit,Credit,Balance from #GetStatement;
END
GO
Thanks for the support and insights shared.
I was able to overcome the issue, by changing the data type for all areas where I had Decimal(18,2) to money. The variable #OpeningBalance Decimal(18,2) was changed to #OpeningBalance money
Same was done for #DebitRecord, #CreditRecord, #NewBalance, #PreviousBalance
Likewise, 'Coalesce' was used for the calculation of the new balance, by coalescing the PreviousBalance, the CreditRecord, and the DebitRecord.
Change These DECLARES:
#NewBalance nvarchar(150),
#PreviousBalance nvarchar(150);
To
#NewBalance DECIMAL(10,2),
#PreviousBalance DECIMAL(10,2);
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
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
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