Using transaction in cursor with try..catch - sql-server

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

Related

Dynamic Cursor SQL Server

I have this global cursor that is created by a string like this, however when execute, I get this error message :
A cursor with the name 'crsDTO' does not exist.
Code:
DECLARE #Cursor NVARCHAR(MAX);
SET #Cursor = 'DECLARE crsDTO CURSOR FOR SELECT p.ID, p.Price, p.Count FROM Business.Products';
exec sp_executesql #Cursor;
OPEN crsDTO; -- fails here <<<<<<<<
BEGIN TRY
FETCH NEXT FROM crsDTO INTO #ID, #Price, #Count;
WHILE 0 = ##fetch_status
BEGIN
PRINT(#ID)
FETCH NEXT FROM crsDTO INTO #ID, #Price, #Count;
END;
CLOSE crsDTO;
DEALLOCATE crsDTO;
END TRY
BEGIN CATCH
CLOSE crsDTO;
DEALLOCATE crsDTO;
END CATCH
I looked around everything looks to be fine.. and I can't find why it's not working.
UPDATE
This SP is going to bulk update either price or stock or both. i might be wrong and there might be alternative way which is much better than this i am open to all correction.
However this cursor is going to be filtered based on user opinion. it can change stock/prices(as percentage amount or basic amount) based on the filters.
so for example user wants bulk change the prices for only specific brandId or combination of BrandId/CategoryId and SupplierId or none of them(which means every product).
CREATE procedure [Business].[Product_BulkUpdate]
(
#PO_Error int OUTPUT,
#PO_ErrorMessage Nvarchar(Max) OUTPUT,
#PO_Step int OUTPUT,
#CallerUserId uniqueidentifier,
#CategoryId uniqueidentifier = null,
#BrandId uniqueidentifier = null,
#SupplierId uniqueidentifier = null,
#ProductName nvarchar(max) = null,
#Amount float = null,
#AmountPercentage float = null,
#IsInStock bit = null
)
as
DECLARE #ID Uniqueidentifier;
DECLARE #Price int;
DECLARE #Count int;
DECLARE #KW nvarchar(max);
DECLARE #Cursor nvarchar(max);
DECLARE #WhereClause nvarchar(max);
set #WhereClause = ' 1=1 ';
if (#ProductName is not null)
set #WhereClause =#WhereClause + ' And p.Name like N'''+'%'+cast(#ProductName as nvarchar(4000))+'%'+''' ';
if (#CategoryId is not null)
set #WhereClause =#WhereClause + ' And c.ID in (SELECT cf.id FROM Business.GetCategoryChilds('''+CAST(#CategoryId as nvarchar(50)) +''') cf) ';
if(#SupplierId is not null)
set #WhereClause = #WhereClause + ' AND p.SupplierId in (' + CAST(#SupplierId as nvarchar(50)) + ') ';
IF(#BrandId is not null)
set #WhereClause = #WhereClause + ' AND bb.ID in (' + CAST(#BrandId as nvarchar(50)) + ')';
SET #Cursor = ' DECLARE crsDTO cursor for
SELECT p.ID, p.Price, p.Count FROM Business.Products p
INNER JOIN Kernel.BaseEntity b on b.ID = p.ID AND b.IsDelete = 0
LEFT JOIN Business.Brand bb on bb.ID = p.BrandId
LEFT JOIN Business.Category c on c.ID = p.CategoryId
LEFT JOIN MarketPlace.Supplier s on s.SupplierId = p.SupplierId
WHERE '+#WhereClause+' AND c.CategoryTypeId = 10700';
begin
--- Auto generated procedure
SET NOCOUNT ON;
SET #PO_Error = 0;
SET #PO_Step = 0;
SET #PO_ErrorMessage = '';
BEGIN TRY
exec sp_executesql #Cursor;
SET #PO_Step = 1;
OPEN crsDTO;
BEGIN TRY
FETCH NEXT FROM crsDTO INTO #ID, #Price, #Count;
while 0 = ##fetch_status
BEGIN
IF(#IsInStock = 0) BEGIN
IF(#Amount is not null and #AmountPercentage is null) BEGIN
IF EXISTS (SELECT ID FROM Business.Products WHERE ID = #ID) BEGIN
UPDATE Business.Products SET
Price = #Price + #Amount
WHERE ID = #ID
END
END else IF(#AmountPercentage is not null and #Amount is null) BEGIN
IF EXISTS (SELECT ID FROM Business.Products WHERE ID = #ID) BEGIN
UPDATE Business.Products SET
Price = (#Price * (#AmountPercentage / 100))
WHERE ID = #ID
END
END
END ELSE IF(#IsInStock = 1) BEGIN
IF(#Amount is not null and #AmountPercentage is null) BEGIN
IF EXISTS (SELECT ID FROM Business.Products WHERE ID = #ID) BEGIN
UPDATE Business.Products SET
Price = #Price + #Amount,
Count = 0
WHERE ID = #ID
END
END else IF(#AmountPercentage is not null and #Amount is null) BEGIN
IF EXISTS (SELECT ID FROM Business.Products WHERE ID = #ID) BEGIN
UPDATE Business.Products SET
Price = (#Price * (#AmountPercentage / 100)),
Count = 0
WHERE ID = #ID
END
END ELSE IF(#Amount is null and #AmountPercentage is null) BEGIN
IF EXISTS (SELECT ID FROM Business.Products WHERE ID = #ID) BEGIN
UPDATE Business.Products SET
Count = 0
WHERE ID = #ID
END
END
END
SET #PO_Step = 2;
FETCH NEXT FROM crsDTO INTO #ID, #Price, #Count;
END;
CLOSE crsDTO;
DEALLOCATE crsDTO;
END TRY
BEGIN CATCH
CLOSE crsDTO;
DEALLOCATE crsDTO;
SET #PO_Error = ERROR_NUMBER();
SET #PO_ErrorMessage = ERROR_MESSAGE();
END CATCH
END TRY
BEGIN CATCH
SET #PO_Error = ERROR_NUMBER();
SET #PO_ErrorMessage = ERROR_MESSAGE();
END CATCH
END;
I would add check if cursor exists:
-- ....
BEGIN CATCH
IF CURSOR_STATUS('global','crsDTO')>=-1
BEGIN
CLOSE crsDTO;
DEALLOCATE crsDTO;
END
END CATCH
db<>fiddle demo
Using global cursor/row-by-row approach does not seems to be the best solution.

Adding a duplicate number

I'm currently experiencing the following problem.
If you have a look at the below test case:
declare #Count int
, #id int = 777
declare #table table
( id int identity primary key
, JCid int
, line int
, udf float )
insert into #table (jcid,line,udf)
values
(777,1,1),
(777,2,2.1),
(777,3,2.2),
(777,4,2),
(777,5,3)
select
#Count = count(left(L.udf,1))
from #table L
where L.jcid = #id
group by left(L.udf,1)
having count(left(L.udf,1))>1
select #Count
When I run this, I get the desired results of 3, however upon developing the below trigger, I can't get the count to work out correctly:
create trigger kv_trg_JobLineNumberUpdate_AW on _btblJCTxLines
after insert, update
as
declare #LineNum float
, #OldLine float
, #id int
, #Count int
, #Err nvarchar(500)
set #Err = '--------------------------';
set #Err = #Err + #Err + CHAR(10);
set #Err = #Err + CHAR(10);
set #Err = #Err + 'You are not allowed to change this Line Number!';
select
#LineNum = iLineID
, #OldLine = isnull(ufJCTxCMLineNumber,0)
, #id = iJCMasterID
from inserted
select
#Count = count(left(L.ufJCTxCMLineNumber,1))
from _btblJCTxLines L
join inserted i on left(L.ufJCTxCMLineNumber,1) = left(i.ufJCTxCMLineNumber,1)
where L.iJCMasterID = #id
group by left(L.ufJCTxCMLineNumber,1)
having count(left(L.ufJCTxCMLineNumber,1))>1
begin
if #OldLine = 0
begin
if #Count >= 2
begin
update _btblJCTxLines
set ufJCTxCMLineNumber = cast(#LineNum as varchar)+'.'+cast(#Count as varchar)
from _btblJCTxLines L
join inserted on L.idJCTxLines = inserted.idJCTxLines
end
else
begin
update _btblJCTxLines
set ufJCTxCMLineNumber = #LineNum
from _btblJCTxLines L
join inserted on L.idJCTxLines = inserted.idJCTxLines
end
end
else
begin
select
#OldLine = deleted.ufJCTxCMLineNumber
, #LineNum = inserted.ufJCTxCMLineNumber
from inserted, deleted
if (#OldLine <> #LineNum)
begin
raiserror(#Err, 16, 1)
rollback tran
return;
end
end
end
go
The ufJCTxCMLineNumber field is the duplicate number I'm looking for.
This triggers main purpose is to ensure that the ufJCTxCMLineNumber field never has duplicates.
What happens is, a user inserts a new line, when they add a new line above any current line, I want the ufJCTxCMLineNumber field to be updated to 3.1 depending on how many duplicates there is.
How would I go about getting the correct count?
Follow this link for Sample Data.

SQL Server can't get current incremented row from table variable

I am running into a problem getting my recursive script to find the current row from a table variable. I have verified that there is data in the table variable. That part is working great, however the next part of my script keeps hitting my else statement. It worked great with temp tables but I am trying to get this into a function so I can call it easier with other scripts.
BEGIN
DECLARE #totalrows INT
DECLARE #currentrow INT = 1
DECLARE #tempTable TABLE (value VARCHAR(255), ID INT)
SELECT * Into #temp FROM dbo.fn_split((SELECT TOP (1) address_full FROM sde.gis.BUSINESS), ' ')
ALTER TABLE #temp
ADD ID INT IDENTITY
INSERT into #tempTable ( value, ID )
SELECT *
FROM #temp
SELECT * FROM #tempTable
DECLARE #address_no MONEY
DECLARE #pre_dir VARCHAR(2)
DECLARE #street_name VARCHAR(45)
DECLARE #suffix VARCHAR(20)
WHILE ( #currentrow <= #totalrows )
BEGIN
DECLARE #cur_value VARCHAR(50)
SELECT #cur_value = value
FROM #tempTable
WHERE id = #currentrow
PRINT 'Working on ' + #cur_value
IF ( #currentrow = 1 )
BEGIN
IF ( ISNUMERIC(#cur_value) = 1 )
SET #address_no = CAST(#cur_value AS MONEY)
ELSE
RETURN
END
IF ( #currentrow = 2 ) -- Is this a direciton
BEGIN
IF EXISTS ( SELECT 1
FROM mead.dbo.street_direction
WHERE street_direction = #cur_value )
BEGIN
SET #pre_dir = #cur_value
END
ELSE
BEGIN
SET #street_name = #cur_value
END
END
IF ( #currentrow > 2 ) -- Is this a direciton
BEGIN
IF EXISTS ( SELECT 1
FROM mead.dbo.street_type
WHERE street_type = #cur_value )
BEGIN
SET #suffix = #cur_value
END
ELSE
BEGIN
IF ( #street_name IS NULL )
SET #street_name = #cur_value
ELSE
SET #street_name = #street_name + ' ' + #cur_value
END
END
SET #currentrow = #currentrow + 1
END
END
SELECT #address_no ,
#pre_dir ,
#street_name ,
#suffix
DROP TABLE #temp
Answered my own question. Forgot to set my totalrows = ##rowcount.

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

Resources