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 2000 Forums
 SQL Server Development (2000)
 Is this the correct way to do a transaction?

Author  Topic 

jesus4u
Posting Yak Master

204 Posts

Posted - 2002-08-06 : 14:08:47
Is this the correct way to do a transaction?


CREATE PROCEDURE dbo.db_InsertQuestion
@msg varchar(250),
@Uid int,
@ViewId int,
@ChatRoomID int
AS

BEGIN TRANSACTION

DECLARE @sendMessages int

INSERT INTO
Questions
(msg,
Uid,
ViewId)
VALUES
(@msg,
@Uid,
@ViewId)

-- update user's message count
SELECT @sendMessages = sendMessages FROM Chatters WHERE id = @Uid AND Chatid = @ChatRoomID
-- increment count
SET @sendMessages = @sendMessages + 1

UPDATE Chatters SET lastAction = getdate(), sendMessages = @sendMessages WHERE id = @Uid AND Chatid = @ChatRoomID

IF @@Error > 0
BEGIN
ROLLBACK TRANSACTION
RETURN
END

COMMIT TRANSACTION



jasper_smith
SQL Server MVP & SQLTeam MVY

846 Posts

Posted - 2002-08-06 : 14:31:02
It's always a good idea to save error and rowcount into local variables after each statement that affects data.


CREATE PROCEDURE dbo.db_InsertQuestion
@msg varchar(250),
@Uid int,
@ViewId int,
@ChatRoomID int
AS
SET NOCOUNT ON

DECLARE @err int ; SET @err = 0
DECLARE @cnt int ; SET @cnt = 0

BEGIN TRANSACTION

INSERT INTO
dbo.Questions
(msg,
Uid,
ViewId)
VALUES
(@msg,
@Uid,
@ViewId)
SELECT @err=@@ERROR,@cnt=@@ROWCOUNT

IF @err<>0 OR @cnt=0
BEGIN
RAISERROR('Insert failed',16,1)
ROLLBACK TRANSACTION
RETURN 1
END

-- update user's message count
UPDATE Chatters
SET lastAction = getdate(), sendMessages = (sendMessages+1)
FROM Chatters
WHERE id = @Uid AND Chatid = @ChatRoomID
SELECT @err=@@ERROR,@cnt=@@ROWCOUNT

IF @err<>0 OR @cnt=0
BEGIN
RAISERROR('Update failed',16,1)
ROLLBACK TRANSACTION
RETURN 1
END

COMMIT TRANSACTION

RETURN



HTH
Jasper Smith
Go to Top of Page
   

- Advertisement -