can anyone help me with raiserror in stored procedure.
My Proc
Alter Proc Proc_Test
as
begin
declare #runID int;
set #runID =
(
select max(isnull([RunID],0)) + 1
from [dbo].[Stored_Proc_Test]);
insert into [dbo].[Stored_Proc_Test]
( RunID,
ServerName,
DatabaseName,
ExecutionUser,
ProcName,
StartDate)
select #runID,
##SERVERNAME,
DB_NAME(),
SYSTEM_USER,
OBJECT_NAME(##procid) as ProcName,
GETDATE () as StartDate;
declare #Countrow int
set #Countrow= (select count(*) from [dbo].[Athletes] )
begin try
truncate table [dbo].[Athletes]
insert into [dbo].[Athletes]
select * from [dbo].[Athletes_Stored]
delete from [dbo].[Athletes_History]
where 1 = 1
insert into [dbo].[Athletes_History]
select * from [dbo].[Athletes]
update [dbo].[Stored_Proc_Test]
set EndDate = getdate (),
RowsAffectec = ##ROWCOUNT,
TaskStatus = 'Complete successfully'
where RunID = #runID
end try
begin catch
update [dbo].[Stored_Proc_Test]
set Runcomments = 'Error on line' + Cast(Error_Line() as varchar(10)),
TaskStatus = 'Failed',
ErrorMsg = Cast(Error_Number() as varchar(20)) + ': '+ ERROR_MESSAGE()
where RunID = #runID
end catch;
end
what I'm trying to do is if table [dbo].[Athletes] is EMPTY stop running the SP and throw message "EMPTY SOURCE". If table is not empty keep running the SP.
Thank you
Related
ALTER PROC usp_test
AS
BEGIN
DECLARE #errorMsg NVARCHAR(MAX) = ''
CREATE TABLE #tmp (id TINYINT)
INSERT INTO #tmp (id)
SELECT 1666555666666
SET #errorMsg =#errorMsg + ISNULL(ERROR_MESSAGE(),'')
INSERT INTO #tmp (id)
SELECT 1
SET #errorMsg =#errorMsg + ISNULL(ERROR_MESSAGE(),'')
INSERT INTO #tmp (id)
SELECT 'a'
SET #errorMsg =#errorMsg + ISNULL(ERROR_MESSAGE(),'')
SELECT #errorMsg
END
Above is my sp and its giving two error and i need to select all error message.
Please guide me for same.
Note: Write now its giving two error but it can be of any number.
This is just sample sp
Try this :
ALTER PROC usp_test
AS
BEGIN TRAN
DECLARE #errorMsg NVARCHAR(MAX) = ''
CREATE TABLE #tmp (id TINYINT)
BEGIN TRY
INSERT INTO #tmp (id)
SELECT 1666555666666
END TRY
BEGIN CATCH
SET #errorMsg =#errorMsg + ISNULL(' - '+ERROR_MESSAGE(),'')
END CATCH
BEGIN TRY
INSERT INTO #tmp (id)
SELECT 1
END TRY
BEGIN CATCH
SET #errorMsg =#errorMsg +ISNULL(' - '+ ERROR_MESSAGE(),'')
END CATCH
BEGIN TRY
INSERT INTO #tmp (id)
SELECT 'a'
END TRY
BEGIN CATCH
SET #errorMsg =#errorMsg +ISNULL(' - '+ ERROR_MESSAGE(),'')
END CATCH
IF #errorMsg=''
COMMIT TRAN
IF #errorMsg<>''
BEGIN
SELECT #errorMsg
ROLLBACK TRAN
END
GO
BEGIN
DECLARE #msg VARCHAR(max);
BEGIN try
SELECT 1 / 0;
END try
BEGIN catch
CREATE TABLE #temp
(
err VARCHAR(100)
);
INSERT INTO #temp
SELECT Error_message() AS ErrorMessage;
SET #msg= (SELECT err
FROM #temp)
PRINT #msg
END catch
END
I have a trigger on a table that executes a stored procedure. The executed stored procedure has a TRY/CATCH, so that if there is an error, a row is inserted into a log table.
When the stored procedure fails, I'm getting the following error:
The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.
How do I make it so the update get committed and the CATCH in the stored procedure is also executed? If I add:
IF ##TRANCOUNT > 0
ROLLBACK TRAN
to the stored procedure, then I get the following error:
The transaction ended in the trigger. The batch has been aborted.
Trigger:
ALTER TRIGGER [dbo].[trigger123] ON [dbo].[tbl321]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE (status)
BEGIN
IF EXISTS (--some condition)
BEGIN
EXEC SProc
END
END
END
SProc:
ALTER PROCEDURE [dbo].[SProc ]
AS
BEGIN
DECLARE #ErrorMessage NVARCHAR(4000);
DECLARE #ErrorSeverity INT;
DECLARE #ErrorState INT;
BEGIN TRY
select #sql = '
declare #error1 varchar(255),
#error2 varchar(255),
#error3 varchar(255)
Exec SomeDB.DBO.ConfirmStatus ''A10594'',#error1 output,#error2 output,#error3 output
if ISNULL(#error1,0) <> 0
begin
set #error1 = ISNULL(#error2,'''') + '' '' + ISNULL(#error3,'''') + '' '' + ISNULL(#error1,0)
RAISERROR (#error1, 16, 1)
end'
from jobs j
exec(#sql) at [linked_server]
update status
set status_prev = 1
END TRY
BEGIN CATCH
SELECT
#ErrorMessage = ERROR_MESSAGE(),
#ErrorSeverity = ERROR_SEVERITY(),
#ErrorState = ERROR_STATE()
INSERT INTO error_log (error_datetime, [error_message])
SELECT
GETDATE(),
'Msg: ' + ISNULL(CONVERT(VARCHAR, ERROR_NUMBER()), 'N/A') + ', Level: ' + ISNULL(CONVERT(VARCHAR, #ErrorSeverity), 'N/A') + ', Line: ' + ISNULL(CONVERT(VARCHAR, ERROR_LINE()), 'N/A') + ', Error: ' + ISNULL(#ErrorMessage, 'N/A')
END CATCH
END
I was able to modify my stored procedure to not use a try/catch. This gets me what I need.
ALTER PROCEDURE [dbo].[SProc ]
AS
BEGIN
DECLARE #error table (error1 varchar(255))
DECLARE #ErrorMessage NVARCHAR(4000);
DECLARE #ErrorSeverity INT;
DECLARE #ErrorState INT;
BEGIN TRY
select #sql = '
declare #error1 varchar(255),
#error2 varchar(255),
#error3 varchar(255)
Exec SomeDB.DBO.ConfirmStatus ''A10594'',#error1 output,#error2 output,#error3 output
if ISNULL(#error1,0) <> 0
begin
set #error1 = ISNULL(#error2,'''') + '' '' + ISNULL(#error3,'''') + '' '' + ISNULL(#error1,0)
select #error1
end'
from jobs j
insert into #error
exec(#sql) at [linked_server]
if exists (select top 1 error1 from #error)
begin
INSERT INTO error_log (error_datetime, [error_message])
SELECT
GETDATE(),
(select top 1 error1 from #error)
else
update status
set status_prev = 1
END
Having a table like this:
CREATE TABLE tmpDelete
(
ID INT IDENTITY(1, 1),
Value DATE
)
GO
Then I declare my procedure like this:
CREATE PROCEDURE [TestSP]
#prmDate DATE
AS
BEGIN
--PRINT '##TRANCOUNT : ' + CAST(##TRANCOUNT AS NVARCHAR(10))
BEGIN TRANSACTION TestTransaction
BEGIN TRY
--PRINT '##TRANCOUNT : ' + CAST(##TRANCOUNT AS NVARCHAR(10))
INSERT INTO dbo.tmpDelete
( Value )
VALUES ( 'abc' -- Value - date
);
COMMIT TRANSACTION TestTransaction
--PRINT '##TRANCOUNT : ' + CAST(##TRANCOUNT AS NVARCHAR(10))
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION TestTransaction
DECLARE #NVERRO_MESS NVARCHAR(4000);
DECLARE #INERR_SEVE INT, #INER_STAT INT;
SELECT #NVERRO_MESS = ERROR_MESSAGE(), #INERR_SEVE = ERROR_SEVERITY(), #INER_STAT = ERROR_STATE();
RAISERROR (#NVERRO_MESS, #INERR_SEVE, #INER_STAT)
--PRINT '##TRANCOUNT : ' + CAST(##TRANCOUNT AS NVARCHAR(10))
RETURN
END CATCH
END
GO
And when I call it from Entity Framework it returns the following error message:
Cannot roll back TestTransaction. No transaction or savepoint of that
name was found. Transaction count after EXECUTE indicates that a
COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count =
%1, current count = %2.
How should I declare my transactions?
I've been doing this stored procedure, however when I execute the stored procedure, I get an infinity execution. This cause a deadlock.
This is the error I got, can someone please help me on this?? Thanks.
Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 2.
Code:
ALTER PROCEDURE [dbo].[spMaterialReceivingCreateItemRequirements]
#DomainSite nvarchar(8),
#ItemNo nvarchar(18),
#tReceiving_id integer,
#SampleRequired integer,
#UserName nvarchar(50)
AS
BEGIN
Declare #ErrorNo integer = '',
#New_JobNo integer,
#Status nvarchar(50) = 'InProcess',
#SPName nvarchar(max) = '',
#intSampleNo integer =1,
#ErrorMessage nvarchar(max) = ''
begin transaction t1
Begin try
BEGIN
--Generate 1 sample for item requirements
set #SampleRequired = 1
WHILE (#intSampleNo <= #SampleRequired)
BEGIN
insert into tItemRequirements
select
domainSite, #tReceiving_id, #ItemNo,
WorkCenter, tStationsType_id,
tSpecTestParameters_descriptions_id,
--row_number() OVER (ORDER BY ID) AS CurrentSet,
1 AS CurrentSet,
#intSampleNo, 1, 'InComplete', getdate(), #UserName
from
tspectestparameters
where
itemno = #ItemNo
set #intSampleNo = #intSampleNo +1
end
END
END TRY
Begin catch
SELECT
#ErrorNo = ERROR_NUMBER(),
#SPName = ERROR_PROCEDURE(),
#ErrorMessage = ERROR_MESSAGE();
rollback transaction t1
end catch
END
BEGIN TRANSACTION t1
BEGIN TRY
BEGIN
--Generate 1 sample for item requirements
SET #SampleRequired = 1
WHILE (#intSampleNo <= #SampleRequired)
BEGIN
INSERT INTO tItemRequirements
SELECT domainSite
, #tReceiving_id
, #ItemNo
, WorkCenter
, tStationsType_id
, tSpecTestParameters_descriptions_id
,
--row_number() OVER (ORDER BY ID) AS CurrentSet,
1 AS CurrentSet
, #intSampleNo
, 1
, 'InComplete'
, getdate()
, #UserName
FROM tspectestparameters
WHERE itemno = #ItemNo
SET #intSampleNo = #intSampleNo + 1
END
END
COMMIT
END TRY
BEGIN CATCH
SELECT #ErrorNo = ERROR_NUMBER()
, #SPName = ERROR_PROCEDURE()
, #ErrorMessage = ERROR_MESSAGE();
ROLLBACK TRANSACTION t1
END CATCH
I know this question might be repeated. I have checked my query more than 2 times but I don't know what is the problem?
Here is my stored procedure with cursor:
ALTER PROCEDURE [dbo].[SPApprove_Request](#Id int, #NumRowsChanged int OUTPUT)
AS
BEGIN TRAN ApprovalTransaction
DECLARE #Mapping_Id int, #C_Id int, #Service_Table varchar(50), #Ser_Id int, #sql nvarchar(4000), #Today_Date datetime
SET #Today_Date=GETDATE()
DECLARE cursorObj CURSOR LOCAL static FOR SELECT serType.Service_Table_Name, serMap.Id, serMap.Request_Id FROM [Service_Type] as serType, [Service_Mapping] as serMap WHERE serType.Id = serMap.Service_Type_Id AND serType.Id IN (SELECT Service_Type_Id FROM Service_Mapping WHERE Request_Id = #Id) and serMap.Request_Id=#Id
OPEN cursorObj
--SELECT ##CURSOR_ROWS AS TotalRows
FETCH NEXT FROM cursorObj into #Service_Table, #Mapping_Id, #C_Id
WHILE ##FETCH_STATUS = 0
BEGIN
SET #sql = 'INSERT into dbo.' + quotename(#Service_Table) + '(Request_Id, Is_Active, Is_Deleted, Is_Cancelled, Created_Date) VALUES (' + #C_Id + ',1, 0, 0,'''+ convert(VARCHAR,#Today_Date) +''')'
EXEC sp_executesql #sql
SELECT #Ser_Id = ##IDENTITY
IF (##ERROR <> 0) GOTO ERR_HANDLER
UPDATE [Service_Mapping] SET Service_Id = #Ser_Id WHERE Id = #Mapping_Id
FETCH NEXT FROM cursorObj into #Service_Table, #Mapping_Id, #C_Id
END
CLOSE cursorObj
DEALLOCATE cursorObj
UPDATE [Request] SET State_Id = 2, Service_State_Id = 1, Approve_Disapprove_Date = #Today_Date, Date_Modified = #Today_Date WHERE Id = #Id
SELECT #NumRowsChanged = ##ROWCOUNT
COMMIT TRAN ApprovalTransaction
RETURN #NumRowsChanged
ERR_HANDLER:
PRINT 'Unexpected error occurred while Approving CRM Request!'
ROLLBACK TRAN ApprovalTransaction
Getting error:
Msg 245, Level 16, State 1, Procedure SPApprove_CRM_Doctor_Request,
Line 19
Conversion failed when converting the nvarchar value 'INSERT
into dbo.[Financial_Assistance](CRM_Doctor_Request_Id, Is_Active,
Is_Deleted, Is_Cancelled, Created_Date) VALUES (' to data type int.
You should convert #C_Id to varchar in order to concatenate it to a string.
SET #sql = 'INSERT into dbo.' + quotename(#Service_Table) +
'(Request_Id, Is_Active, Is_Deleted, Is_Cancelled, Created_Date)
VALUES (' + convert(varchar,#C_Id) + ',1, 0, 0,'''+ convert(VARCHAR,#Today_Date) +''')'
Also you can use sp_executesql system stored procedure with parameters
SET #sql = 'INSERT into dbo.' + quotename(#Service_Table) + '(Request_Id, Is_Active, Is_Deleted, Is_Cancelled, Created_Date) VALUES (#C_Id,1, 0, 0,#Today_Date)'
EXEC sp_executesql #sql, N'#C_Id int, #Today_Date datetime', #C_Id, #Today_Date