Transact SQL :: Error And Transaction Handling For Nested Procedures

Sep 16, 2015

We have a required to run multiple procedures in Single Go . And Error Occurred in any Procedure the it will rollback all the changes( Either all Proc run or None)

DECLARE @StartTime DATETIME=getdate(), @EndTime DATETIME=getdate()-1 , @Message VARCHAR(400)  

BEGIN TRY 
SET XACT_ABORT ON
BEGIN TRANSACTION

EXEC PROC1 @StartTime,@EndTime,@Message OUTPUT --[ Error Handling done here]
EXEC PROC2 @StartTime,@EndTime,@Message OUTPUT --[ Error Handling done here]

[Code] ....

Problem Statement is its not capturing the Error Message from Either Proc1 or Proc 2., its Capturing the Flat Message (The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction). How do i capture the Error Occurred in Proc 1 or Proc 2  into Log Tables.

View 7 Replies


ADVERTISEMENT

Help With Error Handling Please Strored Procedures

Dec 31, 2004

I've got the folloing stored procedure


ALTER PROCEDURE AddUserData
(@login varchar (8),
@password varchar (8),
@fullName varchar (50),
@RoleID Int,
@statusID Int)
AS

if exists
(SELECT login, @errorReturn
FROM tbEmployee
WHERE login = @login)
return 55555
Else
INSERT INTO tbEmployee (login, password, fullname, RoleID, statusId)
VALUES (@login, @password, @fullName, @RoleID, @statusID)

RETURN @@error


the function that calls this stored procedure is this


Public Shared Function InsertUserData(ByVal login As String, ByVal password As String, ByVal fullName As String, ByVal StatusID As Integer, ByVal RoleID As Integer)

' Create the connection object
Dim connection As New SqlConnection(connectionString)
' Create and initilise the command object
Dim command As New SqlCommand("AddUserData", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.Add("@password", SqlDbType.VarChar)
command.Parameters("@password").Value = password
command.Parameters.Add("@login", SqlDbType.VarChar)
command.Parameters("@login").Value = login
command.Parameters.Add("@fullName", SqlDbType.VarChar)
command.Parameters("@fullName").Value = fullName
command.Parameters.Add("@roleID", SqlDbType.Int)
command.Parameters("@roleID").Value = RoleID
command.Parameters.Add("@statusID", SqlDbType.Int)
command.Parameters("@statusID").Value = StatusID
' Open the connection
Try

connection.Open()
command.ExecuteNonQuery()

Finally
connection.Close()
End Try

End Function


now I'm trying to get ahold of the return value from the stored procedure so I can output a message to the user in a label control.

e.g the soted procedure checks to see if a user already exists if it does it returns 55555. how can I get ahold of this 55555 and place it in a variable in the function so I can then send it to another error function to display the approperate lable message ??

thanks all

View 3 Replies View Related

SQL 2012 :: Error And Transaction Handling In Server

May 3, 2015

I'm taking the liberty to announce the availability of a suite of articles on my web site about error and transaction handling in SQL Server. In total there are three main parts and three appendixes.

The first part is a short jumpstart, while Part Two is a long in-depth discussion of what can happen in SQL Server in case of an error and what commands that are available. Part Three covers implementation and has lot of examples as well as a facility for logging and raising errors.

The appendixes cover special areas: linked servers, the CLR and Service Broker.

Start at [URL] ....

View 1 Replies View Related

SQL Server 2008 :: Error Handling In Called Stored Procedures?

Apr 14, 2015

I have one main stored procedure. It calls other 10 stored procedures by giving input parameters.

Do I want to implement Begin Try/Begin catch in each sub procedures or in main procedure only.

View 2 Replies View Related

Linked Server Nested Transaction Error

Oct 10, 2007

I have a problem in running this query on linked servers, which has distributed partitioned view.

SQLTransaction transaction;... public void DeleteAllData() { try { connection.Open(); transaction = connection.BeginTransaction(); { Console.WriteLine("Deleting All Data..."); string cmdText = ""; cmd = new SqlCommand(cmdText, connection, transaction); cmd.CommandText = "delete from NEW_ORDER where NO_O_ID > 0"; cmd.ExecuteNonQuery(); cmd.CommandText = "delete from ORDER_LINE where OL_NUMBER > 0"; cmd.ExecuteNonQuery();
transaction.Commit();
Console.WriteLine("Sucessful"); } } catch (Exception e) { Console.WriteLine("Failed in Method DeleteAllData"); throw e; } finally { connection.Close(); } }

The error returned was:

Failed in Method DeleteAllDataSQL Exception caught: Unable to start a nested transaction for OLE DB provider "SQLNCLI" for linked server "SERVER_B". A nested transaction was required because the XACT_ABORT option was set to OFF.OLE DB provider "SQLNCLI" for linked server "SERVER_B" returned message "Cannotstart more transactions on this session.".

I realized that this problem may be eliminated if I'm using stored procedures on the database, and SET XACT_ABORT ON before any transaction.

Please could anyone help me.

View 1 Replies View Related

Transact SQL :: Program To Catch Transaction Raised Error At The Very End

Aug 11, 2015

I am new to T-SQL programming. I need to write a main procedures to execute multiple transactions. How could I structure the program so that each transaction will not abort if failed. Instead, the next transaction will keep running. At the very end the procedure will output the error and report them back to the main program in the output parameters. Looking for pseudo code.

View 6 Replies View Related

Version Handling Of Procedures?

Nov 6, 2005

I'm involved in the developement/maintanance of a database that has a lot of stored procedures. The procedures are constantly developed and it would be good to have some kind of version handling connected to them.

Is there any way to achive this?

/Lars

View 1 Replies View Related

Handling Transaction

Mar 8, 2004

hi friends,

I like to put a set of sql statements under a transaction and wish the sql server to take care of commit / roll back the entire set depending upon the success/failure of the statements in the set. I want the whole set is either to success or to failure.

When I go through the docs, i find that SQL Server 2000 operates three transaction modes:
Autocommit transactions : Each individual statement is a transaction.

Explicit transactions : Each transaction is explicitly started with the BEGIN TRANSACTION statement and explicitly ended with a COMMIT or ROLLBACK statement.

Implicit transactions: A new transaction is implicitly started when the prior transaction completes, but each transaction is explicitly completed with a COMMIT or ROLLBACK statement.

As one can see, it seems that it is not possible to define "atomic compound sql statements". Even if i used explicit transaction, it is not possible to achieve this, since i couldn't find a mechanism to handle errors for a group of statements.

I wonder how to write atomic compound sql statement in the sql server.
can anybody please help me on this....

Jake

View 2 Replies View Related

Concurrency Handling In Stored Procedures

Jul 23, 2005

I have a requirement that requires detection of rows deleted/updated byother processes. My business objects call stored procedures to create,read, update, delete data in a SQL Server 2000 data store. I've donea fair amount of research on concurrency handling in newsgroups andother resources. Below is what I've come up as a standard forhandling concurrency thru stored procedures. I am sharing with everyoneso I can get some comments (pro/con) regarding this approach and see ifanyone can find any holes for this solution.Below is the DDL, DML and a Stored Proc demonstrating the approach. Iam using a rowversion column for concurrency checking. Another approachthat is less intrusive (doesn't require having a rowversion column inall tables) is using checksum. I may eventually use checksum but theprocess flow should be almost identical. Looking forward to anyone'scomments.Thx, BZ--xxxxxxxxxxxxxxxxxxxxxxxxxxx--IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name ='ApplicationUsers')BEGINPRINT 'Dropping Table ApplicationUsers'DROP Table dbo.ApplicationUsersENDGOPRINT 'Creating Table ApplicationUsers'GOCREATE TABLE dbo.ApplicationUsers(LoginName varchar (20) NOT NULL Primary Key,LoginPassword varchar (50) NOT NULL,LoginAttempts int NOT NULL default(0),EmailAddress varchar(25) NOT NULL Unique,DataVersion rowversion NOT NULL)GOIF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name ='UpdateUser')BEGINPRINT 'Dropping Procedure UpdateUser'DROP Procedure dbo.UpdateUserENDGOPRINT 'Creating Procedure UpdateUser'GOCreate Procedure dbo.UpdateUser@loginName Varchar (20),@loginPassword Varchar (50),@loginAttempts Int,@emailAddress Varchar(25),@dataVersion Rowversion OutputAs/************************************************** ****************************** Name: dbo.UpdateUser** Desc: Updates an Application User instance**** Parameters:** Input** @loginName** @loginPassword** @loginAttempts** @emailAddress** @dataVersion. row version used for concurrency control.**** Output** @dataVersion. updated row version used for concurrencycontrol.**** Return** 0 for Success. Error code if any are encountered** 66661 if current row version doesn't match provided version** 66666 if expected row is not found**************************************************** *****************************/Set NoCount OnDeclare@err Int,@rowCount Int,@tranCount Int--Transaction HandlingSelect @tranCount = @@TRANCOUNTIf (@tranCount=0)Begin Tran LocalTranElseSave Tran LocalTranUpdatedbo.ApplicationUsersSetLoginPassword = @loginPassword,LoginAttempts = @loginAttempts,EmailAddress = @emailAddressWhereLoginName = @loginNameAndDataVersion = @dataVersion--Check for errors and rowCount (Should have updated 1 row)Select @err = @@ERROR, @rowCount = @@ROWCOUNTIf (@err != 0) GOTO ErrHandlerIf (@rowCount != 1) GOTO ConcurrencyHandler--Set dataversion output parameterSelect@dataVersion = DataVersionFromdbo.ApplicationUsersWhereLoginName = @loginName/*If we got this far then there were no errorsIf this proc started transaction then commit it,otherwise return and let caller handle transaction*/If (@TranCount = 0)Commit Tran LocalTranReturn 0/*Rollback local transaction if an error was encountered.Return code is used to communicate error number.*/--Handle Concurrency ErrorsConcurrencyHandler:Rollback Tran LocalTranIf Exists (Select * From dbo.ApplicationUsers where LoginName =@loginName)Return 66661 --Row version doesn't match provided versionElseReturn 66666 --Row not found--Handle Other ErrorsErrHandler:Rollback Tran LocalTranReturn @err --Return Err NumberGOPRINT 'Inserting Test Data...'--Add Test DataInsert Into dbo.ApplicationUsers(LoginName, LoginPassword, LoginAttempts, EmailAddress)Values('blackmamba', 'Pwd1', default, 'bm@DIVAS.com')Insert Into dbo.ApplicationUsers(LoginName, LoginPassword, LoginAttempts, EmailAddress)Values('GoGo', 'Pwd2', default, 'gogo@crazy88.com')GO/*Call UpdateUser Stored Proc with current rowversion*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'Exec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwd', @loginAttempts = 0, @emailAddress = 'bm@DIVAS.com',@dataVersion = @rowvrsn outputPrint @retVal --Should be 0 for successGO/*Call UpdateUser Stored Proc with out of date rowversion (simulateupdate by other process)*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'--Simulate update by other processUpdate dbo.ApplicationUsers Set LoginPassword = LoginPassword whereLoginName = 'blackmamba'--Update User with out of date RowversionExec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwdVersion2', @loginAttempts = 0, @emailAddress ='bm@DIVAS.com', @dataVersion = @rowvrsn outputPrint @retVal --Should be 66661 for rowversion mismatchGO/*Call UpdateUser Stored Proc with out of date rowversion (simulatedelete by other process)*/Declare @retVal int, @rowvrsn rowversion--Get Current Row Versionselect @rowvrsn = DataVersion from dbo.ApplicationUsers where LoginName= 'blackmamba'--Simulate delete by other processDelete From dbo.ApplicationUsers where LoginName = 'blackmamba'--Update User with out of date RowversionExec @retVal = dbo.UpdateUser @loginName = 'blackmamba', @loginPassword= 'UpdatedPwdVersion2', @loginAttempts = 0, @emailAddress ='bm@DIVAS.com', @dataVersion = @rowvrsn outputPrint @retVal --Should be 66666 for row deleted by other process

View 2 Replies View Related

Transaction Handling Problem

May 20, 2008

Hi all i am using Vs 2005 for Web application Development.
At one place i have to update 2 tables and i have to insert in 1 table.For that i am using following function.
But i am getting error pls help me.
My function is.
Public Function UpdateItemDetails(ByVal executemode As ExecuteMode, ByVal Remarks As String, ByVal userid As String, ByVal ItemDetails As ArrayList, ByVal rfsno As String, ByVal rfsstatus As String) As Integer
Try
Dim sql As String
Dim con As New SqlConnection(conString)
con.Open()
cmd.Connection = con
trans = con.BeginTransaction()
cmd.Transaction = trans
''Updating TSMS_RFSITEMDETAILS Table.For Each acc As item1 In ItemDetails
Dim Itemid As String = acc.INameDim quantity As String = acc.QUANTITY
Dim Total As String = acc.TOTAL
sql = "update " + tabPrefix + "RFSITEMDETAILS set QUANTITY=@QUANTITY,TOTAL=@TOTAL,REMARKS=@REMARKS where ITEM_ID=@ITEM_ID"cmd.Parameters.Add("QUANTITY", SqlDbType.NVarChar, 50).Value = acc.QUANTITY
cmd.Parameters.Add("TOTAL", SqlDbType.NVarChar, 255).Value = acc.TOTALcmd.Parameters.Add("ITEM_ID", SqlDbType.Int, 10).Value = acc.INamecmd.Parameters.Add("REMARKS", SqlDbType.NVarChar, 50).Value = Remarks
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()Next
''Updating TSMS_RFS Table.
sql = "update " + tabPrefix + "RFS SET RFS_STATUS=@RFS_STATUS,UPDATEDBY=@UPDATEDBY where RFS_NO=@RFS_NO"
cmd.Connection = concmd.Parameters.Add("RFS_STATUS", SqlDbType.Int, 50).Value = rfsstatus
cmd.Parameters.Add("RFS_NO", SqlDbType.NVarChar, 10).Value = rfsnocmd.Parameters.Add("UPDATEDBY", SqlDbType.Int, 50).Value = userid
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
''Inserting TSMS_ORDER_STATUS_HISTORY Table.
cmd.CommandText = "insert into " + tabPrefix + "ORDER_STATUS_HISTORY(RFS_NO,ORDER_STATUS_ID,UPDATEDBY)values(@RFS_NO1,@ORDER_STATUS_ID,@UPDATEDBY1)"cmd.Parameters.Add("RFS_NO1", SqlDbType.NVarChar, 50).Value = rfsno
cmd.Parameters.Add("ORDER_STATUS_ID", SqlDbType.Int, 50).Value = rfsstatuscmd.Parameters.Add("UPDATEDBY1", SqlDbType.Int, 50).Value = userid
cmd.ExecuteNonQuery()
trans.Commit()Catch ex As Exception
_LastError = ex
trans.Rollback()
Finally
con.Close()
End Try
End Function
 
I am getting following error Second time in For loop when control reached to
cmd.ExecuteNonQuery(). This Statement.
Error is:  The variable name '@QUANTITY' has already been declared. Variable names must be unique within a query batch or stored procedure.
Please Help me.
 

View 2 Replies View Related

Handling SQL Exceptions In CLR Transaction

Sep 28, 2007

Hi there,

We are running into problems using CLR stored procedure in SQL Server 2005.
We are using a transaction scope (ambient transaction).
If an SQL exception with class 16 is thrown, and this exception is directly caught (and handled) then the transaction is somehow no longer valid.
Subsequent use of this transaction gives the message "The current transaction cannot be committed and cannot support operations that write to the log file. Rollback the transaction".

Is there a way to gracefully handle the SqlException and continue the transaction?

Regards,

Frans Z. and Rine le C.



View 1 Replies View Related

Nested Stored Procedures

Nov 25, 2001

I cannot seem to get nesting of stored procedures to work. I must have the syntax wrong. Should the following work:

SELECT *
FROM spWod_rptWoStatusSummary

Where spWod_rptWoStatusSummary is a Stored Procedure.

The above does not work. I get an error telling me that spWod_rptWoStatusSummary is an object that does not exit.

Does anyone know what the correct syntax is?

View 1 Replies View Related

Nested Stored Procedures

Nov 25, 2001

I cannot seem to get nesting of stored procedures to work. I must have the syntax wrong. Should the following work:

SELECT *
FROM spWod_rptWoStatusSummary

(Where spWod_rptWoStatusSummary is a Stored Procedure).

The above does not work. I get an error telling me that spWod_rptWoStatusSummary is an object that does not exit.

Does anyone know what the correct syntax is?

View 1 Replies View Related

Nested Stored Procedures

Dec 5, 2005

Hi Out There

The attempt to create the following stored procedure, which is supposed to call the previously created stored procedures inside it,
causes the following errors.

Server: Msg 137, Level 15, State 2, Line 1
Must declare the variable '@OfferIDTwo'.
Server: Msg 137, Level 15, State 2, Line 1
Must declare the variable '@OfferIDThree'.
Server: Msg 137, Level 15, State 2, Line 1
Must declare the variable '@OfferID'.
Server: Msg 137, Level 15, State 2, Line 1
Must declare the variable '@OfferID'.
Server: Msg 137, Level 15, State 2, Line 1
Must declare the variable '@OfferID'.
Server: Msg 137, Level 15, State 2, Line 1
Must declare the variable '@OfferID'.


Create Procedure spPrepareOfferSimulation
@OfferIDOne int
As
exec spPopulateOfferTables @OfferID
go
exec spPopulateOfferProduct @OfferID
go
exec spPopulateOfferDictionary @OfferID
go
exec spPopulateOfferCondition @OfferID
go
exec spPopulateOfferError @OfferID
go
exec spPopulateOfferLimit @OfferID
go
exec spPopulateOfferQA @OfferID
go


Can someone provide me with some productive input to fix this mess?

View 10 Replies View Related

Nested Stored Procedures

Apr 14, 2008



I have a caller stored procedure (sp_A) which calls several stored procedures (sp_1,sp_2,sp_3,sp_4, sp_5)

The statements in the called stored procedures sp_1 to sp_5 are all contained within BEGIN TRY -- BEGIN TRAN and BEGIN CATCH blocks which ensure that any errors in the SQL statements are rolled back when an error occurs.


However, I have noticed that when the called stored procedure fails, the caller procedure does not fail Rather it continues processing the remaining sps. I want to add code in my calling sp to stop this fom happening. Any ideas?

I have used this statement within my calling sp but no joy yet.

set @ErrCode = 0

exec @ErrCode = sp_executesql @Sql

if @ErrCode <> 0

begin

return 1

end



Any one with ideas? Thanks

View 12 Replies View Related

Nested Stored Procedures.

Sep 28, 2007

I need the output of a stored procedure in another SP. That's simple (using a temporary table). But there's a small (big error ) problem.

Since I have to manually define the temporary table with it's fields and datatype to recieve the output from the nested SP , this approach would fail if, in the future more parameters are required to be returned . Is it possible to immunise my SP to such a consequence at creation time, rather them having to amend the temporary table later ?

Any idea how to overcome the above problem ? Is there a way that the temporary table can be automatically created like we have in a SQL statement with the INTO keyword. Any ideas ?

Thanks,
Alec

View 9 Replies View Related

Nested Stored Procedures

Apr 30, 2008

I have a stored procedure that returns a scalar value and I want to use that value (among other places) within another stored procedure.

-- The general purpose stored procedure is far too long to include here but I've included the last several lines of code at the bottom to show general gist of it and how it exits.--
The only way I can find to use that returned value "criteria" in a stored procedure is to define a temporary table, INSERT it into the table and then extract it from the temprary table into the variable where I actually wanted it.... i.e.

DECLARE @CriteriaTable TABLE ( Criteria VARCHAR(8000) )INSERT INTO @CriteriaTable (Criteria) EXEC psp_WRP_DisplayCriteria @UserID, 'Dealers, Prefix, Serial Range, Models, Makes, Sold Date', @UserGroup SELECT @Criteria=Criteria FROM @CriteriaTable

This seems like a ridiculously long winded and confusing way of doing things, especially since Im doing it in a dozen different procedures, half a dozen reports and 1 (so fasr) asp.net/VB web site - and I can't help thinking there must be a better way using just one or even zero extra lines of code to do this.
e.g. SELECT@Criteria = (EXEC dbo.psp etc...)
... or some variation thereof with the correct syntax.

or even better going to where that variable is used and changing ...
EXEC dbo.[psp_InsertWarrantyReportTracking]
@UserID = @UserID ,
@ReportName = 'rptChassisTrackExtdWarranty', -- <------
@ReportCriteria = @Criteria
to ...
EXEC dbo.[psp_InsertWarrantyReportTracking] @UserID = @UserID , @ReportName = 'rptChassisTrackExtdWarranty', -- <------ @ReportCriteria = (EXEC dbo.psp_ etc...)... or some variation thereof with the correct syntax.

But no matter how I try and how I search I can't find any way other than in what is otherwise a completely supefluous temporary table.

Am I missing something or is that REALLY the only way to get a hold of that returned value?


------ Last portion of the general purpose routine I'm trying to call ---------------------If Patindex('%RO Audit%',@Parmlist) > 0
Begin
set @Criteria = @Criteria + '- RO Audit date'
select @All=ROAuditAll, @From = ROAuditFrom, @To = ROAuditTo
from dbo.tblWRParameters where @UserID = UserName
If @All = 1
set @Criteria = @Criteria + '- ALL' + @NL
else
set @Criteria = @Criteria + 'is between ' + rtrim(@From) + ' and ' + rtrim(@to) + @NL
END


--Return the combined parameter field
select @Criteria as Criteria

END

View 12 Replies View Related

Handling Out-dated Transaction Records

Sep 1, 2006

For performance issue, I believe many program should have a house-keeping procedure to clean up transaction history. Is there any best practice to perform this? Or should it be done simply by moving transaction data from the transaction table into a history table? Any better or consideration that I should be concerned of?

View 1 Replies View Related

Probs In Nested Stored Procedures

Mar 22, 2001

Has anyone faced problems in calling one stored procedure from within another stored procedure ? I am considering using nested SPs, and would appreciate any inputs on it.

Thks,
SC

View 2 Replies View Related

SQL 2012 :: Nested Procedures And Try Catch

Mar 11, 2014

I have 2 Procedures. P1 and P2. Even if there is error in P1 , I want changes in the P2 to be committed. How do I do it?

Following is the code sample I have used for testing. With this code , update in both the procedures are rolled back.

create procedure P2
as
begin try

BEGIN tran
update table1
set Description = '*P2*' + Description
where Code = 'b'

[Code] ....

View 2 Replies View Related

How Do You NOT Rollback Some Code In Nested Procedures?

Apr 29, 2008

I have a procedure that calls other procedures which in turn call other procedures. I have a transaction in the first procedure since I want to rollback everything done if something goes wrong except for rows inserted in a loggtable in my database. The reason for this is that all error shall be saved in this table, otherwise there is no way to find out what error occured.

How do you solve this?

View 4 Replies View Related

REAL Project ETL Package Transaction Handling

Dec 9, 2007

Hello,
I am reading Microsoft REAL project ETL part. I find that it uses neither transaction nor checkpoints throughtout the packages. I am wondering if something goes wrong with the process and the process aborts in the middle,how are we going to handle this. Any particular reson not using transaction? Is it best practice without using transaction for performance consideration and log volumn? I am new to SSIS. I would like to follow the best practice. Thanks for advice..


Regards

Jerry

View 6 Replies View Related

Select Statements And Nested Stored Procedures

Mar 21, 2008

I have nested a Stored Procedure within a stored procedure. The nested stored procedure ends in a select statement. What I'd like to do is either capture the results of the select statement (it will be 1 row with 3 columns, I only need the contents of first column), or suppress the select statement from displaying in the final results of the Stored Procedure it is nested in.

Is there any way to do either of those?

View 1 Replies View Related

T-sql Try Catch - Using Triggers And Nested Stored Procedures

Jan 7, 2008

For every trigger and stored procedure I have a try-catch that writes to an error_log table.
The problem is the inner error is not preserved, always get:
The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.

As seen below - though commented out:
I tried commiting any transactions - though I didn't create one.
I played with the
XACT_STATE though that was 0
My test case was last procedure has 1/0

Thanks,
Russ
-----------------------------------------------------------

Below is what I have

Step 1)

ALTER Trigger [trg_ActivityLogEntryReportsError] ON [dbo].[ActivityLog]
FOR INSERT AS

DECLARE @ActivityLogID int
,@AlertMessageTypeID int
,@comment nvarchar(max)
,@Error_Source nvarchar(max)
--- etc.
SELECT
@ActivityLogID = ActivityLogID
,@AlertMessageTypeID = AlertMessageTypeID
,@Comment = Comment
FROM INSERTED
BEGIN TRY

if @AlertMessageTypeID = 2 -- activity reported an error
begin
exec proc_CreateAlertLogEntry_forError
@ActivityLogID
,@Comment

update ActivityLog
set flgActivityChecked = 1
where @activityLogId = activityLogID
end
END TRY


BEGIN CATCH
select
@Error_Source = 'trg_ActivityLogEntryReportsError '
,@Error_Procedure = ERROR_Procedure()
--- etc.
INSERT INTO ERROR_LOG
( Error_Source
,Error_Procedure
,Error_Message
--- etc.
)
VALUES
(
@Error_Source
,@Error_Procedure
,@Error_Message
---etc.
,@Error_Comment )
-- if @@TRANCOUNT > 0
--begin
--commit
--end
END CATCH

Step 2)

/*
This will be called by a Trigger
*/
ALTER Procedure [dbo].[proc_CreateAlertLogEntry_forError]
(@ActivityLogID int
,@Comment nvarchar(max))
AS

Declare
@ProcessScheduleID int
,@ProcessID int
--,@comment nvarchar(max)
,@Error_Source nvarchar(max)
---etc
BEGIN TRY
insert into AlertLog
(
AlertMessageTypeID
,comment
,ActivityLogID
)
values
(
2 -- error
,@comment
,@ActivityLogID
)

end

END TRY


BEGIN CATCH
PRINT 'ERROR OCCURED'
PRINT ERROR_Procedure() + ' ' + ERROR_MESSAGE()
select
@Error_Source = 'proc_CreateAlertLogEntry_forError '
---etc.
INSERT INTO ERROR_LOG
( Error_Source
,Error_Procedure
,Error_Message
---etc.
)
VALUES
(
@Error_Source
,@Error_Procedure
,@Error_Message
--- etc.)

-- if @@TRANCOUNT > 0
--begin
--commit
--end
END CATCH

update ActivityLog
set
flgActivityChecked = 1
,UpdatedDate = getdate()
,UpdatedBy = suser_sname()
where
ActivityLogID = @ActivityLogID


STEP 3

ALTER Trigger [trg_AlertLogEntry_SendsOnInsert] ON [dbo].[AlertLog]
FOR INSERT AS

declare
@AlertLogID Int
,@AlertMessageTypeID int
,@Comment nvarchar(max)
,@Error_Source nvarchar(max)
,@Error_Procedure nvarchar(max)
,@Error_Message nvarchar(max)
--- etc.
SELECT
@AlertLogID = AlertLogID
,@AlertMessageTypeID = AlertMessageTypeID
,@Comment = isnull(Comment,'')
,@ActivityLogID = isnull(ActivityLogID,-1)
FROM INSERTED

BEGIN TRY

PRINT 'trg_AlertLogEntry_SendsOnInsert'
PRINT @COMMENT
exec proc_SendEmail
@AlertLogID
,@AlertMessageTypeID
,@comment
,@ActivityLogID


END TRY


BEGIN CATCH

select
@Error_Source = 'trg_AlertLogEntry_SendsOnInsert '
,@Error_Procedure = ERROR_Procedure()
,@Error_Message = ERROR_MESSAGE()
--- etc.
INSERT INTO ERROR_LOG
( Error_Source
,Error_Procedure
-- etc.)
VALUES
(
@Error_Source
,@Error_Procedure
,@Error_Message
---etc.)
-- if @@TRANCOUNT > 0
--begin
--commit
--end
END CATCH



STEP 4

ALTER Procedure [dbo].[proc_SendEmail]
(
@AlertLogID Int
,@AlertMessageTypeID int
,@Comment nvarchar(max) = ''
,@ActivityLogID int = -1
)


AS

declare @AlertSubject nvarchar(512)
,@AlertBody nvarchar(max)
,@myQuery nvarchar(512)
,@profile_name1 nvarchar(128)
,@return_value int
,@mymailitem int
,@Error_Source nvarchar(max)
---etc.
,@Error_Comment nvarchar(max)
,@Test int
/*
@return_value int -- not using at this point but 0 is OK 1 is failure
@mymailitem int -- not using now could store mailitem_id which is on msdb.dbo.sysmail_mailitems
sysmail_mailitems.sent_status could be either 0 new, not sent, 1 sent, 2 failure or 3 retry.
*/

select top 1 @profile_name1 = [name] from msdb.dbo.sysmail_profile
order by profile_id

set @profile_name1 = rtrim(ltrim(@profile_name1))
print '@profile_name1: ' + @profile_name1
print '@comment: ' + @comment
Declare @CrsrRecipient Cursor

BEGIN TRY
PRINT 'proc_SendEmail'
--set @test = 1/0 'test crashing
select
@AlertSubject = 'AlertSubject'
,@AlertBody = 'AlertBody'

,@recipients = 'russ@test.com'


print 'sending email ' + CAST(getdate() as nvarchar(100))
EXEC @return_value = msdb.dbo.sp_send_dbmail
@profile_name = @profile_name1
,@recipients = @EMAILID
,@body = @AlertBody
,@subject = @AlertSubject
,@mailitem_id = @mymailitem OUTPUT

print 'Done ' + CAST(getdate() as nvarchar(100))
print cast(@return_value as nvarchar(100))



update alertlog
set AlertSendStatusID = 1 --sent
where
@AlertLogID = AlertLogID

END TRY

BEGIN CATCH
PRINT 'ERROR OCCURED'
PRINT ERROR_Procedure() + ' ' + ERROR_MESSAGE()
select
@Error_Source = ' proc_SendEmail '
,@Error_Procedure = ERROR_Procedure()
--- etc.
INSERT INTO ERROR_LOG
( Error_Source
,Error_Procedure
---etc.)
VALUES
(
@Error_Source
,@Error_Procedure
,@Error_Message
--- etc.)


update alertlog
set AlertSendStatusID = 2 --error
where
@AlertLogID = AlertLogID

--if @@TRANCOUNT > 0
--begin
--commit
--end
END CATCH

View 5 Replies View Related

Nested Procedures &&amp; Using Signature Based Security

May 17, 2006

I am currently developing a project that requires a server level permission for one stored procedure (ALTER ANY LOGIN)

To this effect, I plan to create a certificate, sign the stored procedure with it, import the certificate into the master DB and assign privileges.

I also understand that modification to the code invalidates the signature (after all thats the point of signing something).

But what about user defined functions and stored procedures referenced by the signed procedure? Does SQL server follow the dependancy chain and include referenced procedures in the signature? Or does the privilege assigned to the certificate not apply when the nested procedure is executed?

If this is not the case couldn't a restricted database user just alter a nested stored procedure they have been granted ALTER access to and make themselves SA or something?

So to sum up, do you have to duplicate the functionality of otherwise nested procedures into a certificate signed procedure to protect server security?





View 3 Replies View Related

Enable Error Handling When Writing Custom Source Component /custom Error Handling Component.

Apr 21, 2006

1) We are writing a custome Source component for Oracle with OCI calls, Could some one please let me know how to Enable Error Handling for the Same,

2) Is it possible to write Custome Error Handeling Component for SSIS? if yes could you please help me on how to write it.

Thanks in advance.

View 1 Replies View Related

Handling SQL RollBack Transaction For More Records In A Single Process

Mar 6, 2008

I have over 500 transaction records in a single DB process handling within SQL transaction (Begin, Commit, RollBack and End).
Is there any limitation for the following rollbacktransaction function to handle more records (eg. over 500 records)? Public Shared Sub RollBackTransaction()
Dim transactionObj As Object
Try
transactionObj = SqlTransaction.GetExistingTransaction
If (Not IsNothing(transactionObj)) Then
CType(transactionObj, SqlTransaction).RollBack()
End If

Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Sub
 
 

View 2 Replies View Related

Temp Table Scope In Nested Stored Procedures

Jun 8, 2001

We are migrating a SQL 6.5 application with 1900 stored procedures that use 100's of temp tables to SQL 2000.

A problem we have encountered was that we started out getting an "invalid column" errors on certain procedures. Investigation determined that the error was being generated in a nested procedure. The table that caused the error ended up being a temp table that was created using "select into". The following select statement from that temp table gave the invalid column error.

First thinking it was the "Select Into" we then discovered that the outer most procedure had created a temp table of the same name prior to executing the lower level procedure. After the select into, the next statement was a SELECT that went against what it thought was the inner temp table. However, it grabbed the outermost temp table and then couldn't find the appropriate columns and generated the error.

The solution, of course, was to rename the inner most temp table. We also remove the "select into" in the procedure by explicitly creating the temp table.

We tried creating some test procedures to attempt to reproduce this scenario without complete success.

Our test created 3 procedures (sp1 calling sp2 calling sp3) to mimic the current scenario. Sp1 created a temp table and executed sp2, which executed sp3. Sp3 created another temp table using the same name as the one created in sp1.

If we create all three procedures at the same time, it doesn't matter if we change the order in which they are created or whether we create the inner temp table explicitly or with a "select into", SQL Query Analyzer won't let us create the procedure because it finds that the temp table has been declared twice. If we create the procedures separately however, they compile and allow sp3 to create a temp table by the same name as sp1. After creating the procedures independently, they runs properly in all cases with everything in proper scope and no problems.

Admittedly, this is bad coding to start with, but what is happening with the scope of the temp tables within the stored procedures?

Thanks,
Glen Smith

View 1 Replies View Related

Nested Queries, Stored Procedures, Temporary Table

Jul 23, 2005

Hi,I'm adapting access queries to sql server and I have difficulties withthe following pattern :query1 : SELECT * FROM Query2 WHERE A=@param1query 2: SELECT * FROM Table2 WHERE B=@param2The queries are nested, and they both use parameters.In MS Acccess the management of nested queries with parameters is soeasy (implicit declaration of parameters, transmission of parametersfrom main query to nested query)that I don't know what the syntax should be for stored procedures.The corresponding stored procedure would be something likeCREATE TABLE #TempTable (...table definition...)INSERT INTO #TempTable ExecProc spQuery2 @Param2SELECT * FROM #TempTable WHERE A=@Param1And spQuery2 would be : SELECT * FROM Table2 WHERE B=@ParamI was wondering if this syntax would work and if I can skip theexplicit declaration of #TempTable definition.Thanks for your suggestions.

View 5 Replies View Related

Why The Log File Is Growing Too Much Upon Running Nested Stored Procedures (MS SQL 2K)

Feb 11, 2006

Hi there,I have a data manipulation process written in a Nested Stored procedurethat have four levels deeper. When I run these individual proceduresindividually they all seems to be fine. Where as when I run them alltogether as Nested proces (calling one in another as sub-procedures) Logfile is growing pretty bad like 25 to 30GB.. and finally getting kickedafter running disk space. This process is running around 3hrs on a SQLserever Standard Box having dual processer and 2gb ram.This procedures have bunch of bulk updates and at least one cursor ineacch procedure that gets looped through.I was wondering if anybody experienced this situation or have any clueas to why is this happening and how to resolve this?I am in a pretty bad shape to deliver this product and in need of urgenthelp.Any ideas would be greatly appreciated..Thanks in advance*** Sent via Developersdex http://www.developersdex.com ***

View 1 Replies View Related

Create Report With Complex And Nested Stored Procedures

Apr 16, 2007

Hi all,

I had developed all my reports using CRXI and stored procedures of MSSQL 2000. Now I am migrating from CRXI to SSRS. But i have a problem because of my report stored procedures. These stored procedures are complex and nested. When i try to use procedures in a report, it gives a error. When i comment out my EXEC line in my procedures, it goes OK.

Please help me to do this ?

View 1 Replies View Related

T-SQL (SS2K8) :: Varbinary (max) Parameters In Nested Stored Procedures By Value Or Reference

Sep 15, 2014

Consider a situation where a stored procedure taking a varbinary(max) (BLOB) input parameter then calls a nested stored procedure and passes along that varbinary(max) as an input parameter to the nested stored procedure.

Is a copy of the BLOB provided to the nested stored procedure (passed by value) OR is the BLOB passed by reference.

My interest is in understanding the potential memory hit when handling large BLOBs in this environment.

For example, if the BLOB is 200MB, will SQL server need to allocate memory for a new copy each time it's passed to another stored procedure?

Looks like table type parameters are passed by reference, but I haven't been able to find any info on BLOBS in this context.

View 8 Replies View Related

How To Invoke Nested Stored Procedures In SQL Server Projects In VS.NET 2005?

Jul 9, 2006

Hi,


I would like to use a stroed procedure within another stored procedure ( nested sp )

in a SQL project in VS.NET 2005. Since I have to use "context connection = true" as

connection string, I wont be able to use this connection for another sqlconnection

object. Because its already open. and If i try to use a regular connection string

("server=localhost;...") it will raise a security permission error. Having this

problem, Im not able to use nested stored procedures. Would anyone please give me a

hint how to resolve this issue?

View 4 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved