ahmed_sa Ответов: 1

Как остановить выполнение и не продолжать его, если хранимая процедура имеет ошибку ?


I work on SQL server 2012 

I have stored procedure as below 

the stored procedure delete from two tables tradecode and tradecodecontrol

i forget to get column from excel sheet so it is continue execution and delete from database  although it have error on first block when get data from input file

so i need before delete stop execution if stored procedure have error execution before delete 

so what i do 

mu delete stored procedure as below :


Что я уже пробовал:

ALTER PROC [dbo].[sp_DeleteTradeCodesByPlImporter] 

@ImportFilePath varchar(500) ,
@ExportFilePath varchar(500)





AS

BEGIN
create table #TempPC 
(
[ID] INT IDENTITY,
ZPL NVARCHAR(300) NOT NULL,
ZPLID INT,
CodeType nvarchar(100),
CodeTypeId int,
[Status] NVARCHAR(250)
)

DECLARE @sql NVARCHAR(MAX)='INSERT into #TempPC 
( 
ZPL,
CodeType
)
select ZPL,CodeType FROM OPENROWSET( ''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0 Xml;HDR=YES;Database=' + @ImportFilePath + ''',''SELECT ZPL,CodeType FROM [Sheet1$]'')' 

EXEC(@sql)
Declare @CreatedBy int = (select InsertedBy from ImporterQueue where filepath = @ImportFilePath);


UPDATE t SET t.ZPLID=TCDC.ZPLID
FROM #TempPC t 
INNER JOIN dbo.Nop_AcceptedValuesOption AVO ON AVO.AcceptedValuesID=110 AND t.ZPL=AVO.Name 
LEFT OUTER JOIN Parts.TradeCodeControl TCDC ON AVO.AcceptedValuesOptionID=TCDC.ZPLID 



UPDATE t SET t.[Status]='Not Existing In the Table To be Deleted'
FROM #TempPC t WHERE t.ZPLID IS NULL

UPDATE t SET t.CodeTypeId=TCDC.CodeTypeID
FROM #TempPC t 
INNER JOIN dbo.Nop_AcceptedValuesOption AVO ON AVO.AcceptedValuesID=5652 AND t.CodeType=AVO.Name 
LEFT OUTER JOIN Parts.TradeCodeControl TCDC ON AVO.AcceptedValuesOptionID=TCDC.CodeTypeID 
// here i need to stop stored procedure execution if it have error before


DELETE TCC FROM #TempPC t INNER JOIN Parts.TradeCodes TCC ON t.ZPLID=TCC.ZPLID where  ((t.CodeTypeId IS NULL ) OR TCC.CodeTypeID=t.CodeTypeId) AND t.Status is null

DELETE TCC FROM #TempPC t INNER JOIN Parts.TradeCodeControl TCC ON t.ZPLID=TCC.ZPLID where  ((t.CodeTypeId IS NULL) OR TCC.CodeTypeID=t.CodeTypeId) AND t.Status is null





DECLARE @Import NVARCHAR(max)= 'INSERT INTO OPENROWSET(''Microsoft.ACE.OLEDB.12.0'',''Excel 12.0 Xml;HDR=YES;Database='
+@ExportFilePath + ''',''SELECT ZPL,CodeType,Status FROM [Sheet1$]'') select 
ZPL,CodeType , [Status] from #TempPC'



EXEC(@Import) 

end

1 Ответов

Рейтинг:
2

OriginalGriff

Использовать TRANSACTION с собой TRY ... CATCH блок:
Транзакции SQL - w3resource[^]
ПРОБОВАТЬ...CATCH (Transact-SQL) - SQL Server | Microsoft Docs[^]