Results 1 to 18 of 18

Thread: Call SQL Server stored procedure from C# and determine commit or rollback

  1. #1

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    My Mustang GT
    Posts
    4,566

    Call SQL Server stored procedure from C# and determine commit or rollback

    Code:
    CREATE PROCEDURE xsp_DeleteThis
    	@pk int
    AS
    BEGIN
    
    SET XACT_ABORT ON
    
    	BEGIN TRANSACTION
    		
    		UPDATE tblX SET ... WHERE pk = @pk
    			
    		UPDATE tblY SET ... WHERE pk = @pk
    		
    		UPDATE xtblZ SET ... WHERE pk = @pk
    
    	COMMIT TRANSACTION
    
    END
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  2. #2

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    My Mustang GT
    Posts
    4,566

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    I have a few basic questions.

    Is that a good way to write a stored procedure where I want all UPDATE's to be atomic?

    Is the rollback implied by the directive SET XACT_ABORT ON?

    In my C# code, what will I get back if the call fails/succeeds?

    Thanks, I know these are simple questions but I am not getting the right hits when I google. And in case you're wondering why a delete sp updates...I am setting fields in each of the three tables that will indicate the record is "deleted" but not actually delete it.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  3. #3
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    What do you think will fail with your UPDATE statements?

    I would rather use "If @@RowCount<>1..." and then handle an error in an update that hits no records.

    But again - what are you expecting to fail?

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  4. #4
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    That is incorrect use of SET XACT_ABORT - it does not go in a STORED PROCEDURE.

    "The setting of SET XACT_ABORT is set at execute or run time and not at parse time."

    https://msdn.microsoft.com/en-us/library/ms188792.aspx

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  5. #5
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    I still want to know what "errors you are expecting".

    But regardless - look at TRY/CATCH

    https://msdn.microsoft.com/en-us/library/ms175976.aspx

    and also understand that some errors are not catchable. Usually none of the ones you would expect

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  6. #6

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    My Mustang GT
    Posts
    4,566

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    I don't expect any code that I write to fail. Yet occasionally it does .

    But in this particular scenario, you are right. So you recommend stripping out the transaction stuff and just running three updates? Also, RowCount may be more than 1. I know I mislead you calling the param PK, but it's actually more of an FK but not officially. So if I wanted to make sure I update at least one row before going onto the next update, I would check >0, I guess.

    I don't know...I'm converting vb6 code and trying to make it better instead of just doing a brainless convert. The original code sent 1st update to db, sent 2nd update to db, sent 3rd, and that's it. I thought I would combine into an SP and call once and add error checking.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  7. #7
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    Wow - forum will not let me post code!! I'll post an image!!!
    Attached Images Attached Images  
    Last edited by szlamany; Aug 9th, 2016 at 09:40 AM.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  8. #8
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    forum is broken
    Attached Images Attached Images  

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  9. #9

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    My Mustang GT
    Posts
    4,566

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    I know! That's why I posted this info in two parts! Was trying since yesterday. Go to Forum Feedback you will see it's a known issue.
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  10. #10

    Thread Starter
    PowerPoster MMock's Avatar
    Join Date
    Apr 2007
    Location
    My Mustang GT
    Posts
    4,566

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    Would I also want to SELECT GotError so it goes back to my code, so my code can know if sproc succeeded or failed? Or, can the code know if the commit or the rollback happened?
    There are 10 kinds of people in this world. Those who understand binary, and those who don't.

  11. #11
    A SQL Server fool GaryMazzone's Avatar
    Join Date
    Aug 2005
    Location
    Dover,NH
    Posts
    7,493

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    You could add a throw in the proc I guess. Or add an output to capture the error code and return that
    Sometimes the Programmer
    Sometimes the DBA

    Mazz1

  12. #12
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    I like to do a "SELECT @GotError" usually - and just look for that result.

    Or I get more sophisticated with something like this

    [code]Use Acctfiles
    Go
    SET QUOTED_IDENTIFIER ON
    GO
    SET ANSI_NULLS ON
    GO
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[infCashBookSummary_Action]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    drop procedure [dbo].[infCashBookSummary_Action]
    GO
    Create Procedure infCashBookSummary_Action
    @ctrlval1 varchar(100)
    ,@ctrlval2 varchar(100)
    ,@ctrlval3 varchar(100)
    ,@CloseDate varchar(100)
    ,@EndDate varchar(100)
    ,@CashType varchar(100)
    ,@Net varchar(100)
    ,@Fiscal_Year int
    ,@Date_to_Run datetime
    as

    Set NoCount On

    If IsNull(@ctrlval3,'')='Delay Activity'
    Begin
    Update CashClose_T
    Set CashAction=@ctrlval3
    , CloseDate=DateAdd(mm,1,CashDate)
    Where CCId=@ctrlval1
    Select '["reload", "display"]'
    Return
    End

    If IsNull(@ctrlval3,'')='Restore Activity'
    Begin
    Update CashClose_T
    Set CashAction=''
    , CloseDate=CashDate
    Where CCId=@ctrlval1
    Select '["reload", "display"]'
    Return
    End

    If IsNull(@ctrlval3,'')='Delete Activity'
    Begin
    Delete From CashClose_T
    Where CCId=@ctrlval1
    Select '["reload", "display"]'
    Return
    End

    If IsNull(@ctrlval3,'')='Add Activity'
    Begin
    If IsNull(@EndDate,'')=''
    Begin
    Select '["errormessage", "End Date cannot be blank"]'
    Return
    End
    If IsDate(@EndDate)=0
    Begin
    Select '["errormessage", "End Date must be a valid date"]'
    Return
    End
    If DatePart(yyyy,@Date_to_Run)<>DatePart(yyyy,@EndDate)
    or DatePart(MM,@Date_to_Run)<>DatePart(MM,@EndDate)
    Begin
    Select '["errormessage", "Date is not in the correct month and year"]'
    Return
    End
    If IsNull(@CashType,'')=''
    Begin
    Select '["errormessage", "Type cannot be blank"]'
    Return
    End
    If IsNull(@Net,'')=''
    Begin
    Select '["errormessage", "Net cannot be blank - must enter a number"]'
    Return
    End
    If IsNumeric(@Net)=0
    Begin
    Select '["errormessage", "Net must be a valid number"]'
    Return
    End
    If Cast(@Net as money)=0
    Begin
    Select '["errormessage", "Net must be a non-zero entry"]'
    Return
    End
    Insert into CashClose_T values (@Fiscal_Year, @CloseDate, @CloseDate, 'Y', '', 0, @EndDate, @CashType, @Net, null, null, null, 4, GetDate())
    Select '["reload", "display"]'
    Return
    End

    Select '["errormessage", "No Action with command: ' + IsN
    Last edited by szlamany; Aug 9th, 2016 at 12:25 PM.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  13. #13
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    we use Return 0 for success or Return 1 for fails at the end of our sprocs:
    Code:
    	end
    end try
    
    begin catch
    	exec dbo.USP_RAISE_ERROR; -- <- custom sproc for handling errors
    	return 1;
    end catch
    
    
    return 0;
    then from code the return value parameter can be checked.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  14. #14
    PowerPoster abhijit's Avatar
    Join Date
    Jun 1999
    Location
    Chit Chat Forum.
    Posts
    3,228

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    One thing I can suggest is to not have COMMIT / ROLLBACK statements in your stored procedures if the procedure is being called from a client application.
    Let the client application control the transaction handling in its code.
    Everything that has a computer in will fail. Everything in your life, from a watch to a car to, you know, a radio, to an iPhone, it will fail if it has a computer in it. They should kill the people who made those things.- 'Woz'
    save a blobFileStreamDataTable To Text Filemy blog

  15. #15
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    Quote Originally Posted by abhijit View Post
    One thing I can suggest is to not have COMMIT / ROLLBACK statements in your stored procedures if the procedure is being called from a client application.
    Let the client application control the transaction handling in its code.
    I never hold a transaction open from the client side - I would recommend against that normally.

    What benefit have you found in doing this?

    I am always concerned about some client code hanging with an error message or something like that and holding that lock on the database being a bad thing.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  16. #16
    PowerPoster abhijit's Avatar
    Join Date
    Jun 1999
    Location
    Chit Chat Forum.
    Posts
    3,228

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    Quote Originally Posted by szlamany View Post
    I never hold a transaction open from the client side - I would recommend against that normally.

    What benefit have you found in doing this?

    I am always concerned about some client code hanging with an error message or something like that and holding that lock on the database being a bad thing.
    What if the client code has to fire several stored procedures?
    You wouldn't want to commit in between.
    It is easier to control the entire transaction through the client.
    Everything that has a computer in will fail. Everything in your life, from a watch to a car to, you know, a radio, to an iPhone, it will fail if it has a computer in it. They should kill the people who made those things.- 'Woz'
    save a blobFileStreamDataTable To Text Filemy blog

  17. #17
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    I never find myself firing sequential SPROC calls without WANTING them to each commit.

    If I am saving a dozen grid rows to a table I want each row to commit.

    If I need to have all of them be "inserted" at once I would load into a staging table and upon the success of that non-locking operation then call a single SPROC to process all those rows at once.

    As much as you find it easier to control the transaction through the client I would argue as much for transaction control within the SPROC.

    Different philosophies - both valid.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  18. #18
    New Member
    Join Date
    Aug 2016
    Posts
    9

    Re: Call SQL Server stored procedure from C# and determine commit or rollback

    Like a lot of things, it depends... typically I try to keep transactions as small as possible... keep them in the db if I can... but there have been cases where it can only be done from the client. I used to work on a system where we were processing & updating data across multiple servers... so we'd spin up a distributed transaction from the client, perform the updates, then either commit or rollbakc.... actually where the transaction is created wasn't on the client,but from the app server as part of a services call... but still... it point was that hte transaction was outside the db. It really just depends on your needs.

    -tg

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width