Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 one stored proc with two execute statements issue

Author  Topic 

adlo
Posting Yak Master

108 Posts

Posted - 2010-04-28 : 13:13:36
I have one stored proc with two execute statements.

exec(...)
Go
exec (..)
Go

The second exec returns the records

How do I ensure that in between the two execs another user does not change the records?

Table1
ColA,ColB,ColC..

The two execs is limited both to ColB that is fixed but have to be seperate execs

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-28 : 13:26:56
You'll need to wrap it into a transaction.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

adlo
Posting Yak Master

108 Posts

Posted - 2010-04-28 : 13:48:53
Do you mean:

begin transaction
go
...
exec
go
exec
go
..
Commit
go
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-28 : 13:59:55
Yes, but you'll need to add error handling. Since you are using 2005, you should do the transaction inside a TRY/CATCH block.

Here's an example from something I wrote last year (code changed to protect proprietary stuff):

BEGIN TRY
BEGIN TRAN

INSERT INTO ...

DELETE ...


COMMIT TRAN
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN

IF ERROR_NUMBER() = 1205 AND @retries < @maxRetries -- 1205 is deadlock error
BEGIN
SET @retries = @retries + 1
WAITFOR DELAY '00:00:10'
END
ELSE -- some other error or done retrying
BEGIN
SELECT
@errorMessage = ERROR_MESSAGE(),
@errorSeverity = ERROR_SEVERITY(),
@errorState = ERROR_STATE();


RAISERROR (@errorMessage, @errorSeverity, @errorState);

RETURN
END
END CATCH


I'm handling deadlocks on this one, but the point really is that it is properly handling errors. When you use a transaction, you have to include COMMIT when there aren't any errors and then ROLLBACK when there are errors.

In 2000, we didn't have TRY/CATCH so the code would be different. We'd have to check @@ERROR after each DML statement to determine whether to continue, COMMIT, or ROLLBACK.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

adlo
Posting Yak Master

108 Posts

Posted - 2010-04-28 : 16:42:54
Thanks for your example.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-28 : 17:27:00
You're welcome, glad to help.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -