在存储过程中使用多个更新语句时处理返回值的最佳方法是什么。
我在数据适配器中使用这个存储过程,并试图获取更新结果总数。
我正在使用SQL Server 2008和 .NET 4.5
例如:
CREATE PROCEDURE [dbo].[usrsp_MessageConversation_delete]
(
@fromMbrID int,
@toMbrID int
)
AS
BEGIN
SET NOCOUNT OFF;
UPDATE mbr_Messages
SET fromDeleted = 1
WHERE (fromMbrID = @fromMbrID) AND (toMbrID = @toMbrID)
UPDATE mbr_Messages
SET toDeleted = 1
WHERE (fromMbrID = @toMbrID) AND (toMbrID = @fromMbrID)
//RETURN TOTAL NUMBER OF UPDATED RECORDS
EG: RETURN @@ROWCOUNT ??
END
我想返回更新记录的总数,如果没有更新,则返回 0。
我是否需要添加任何其他错误处理 - 如果需要,有什么建议吗?
更新:我最终选择了这个:
BEGIN
SET NOCOUNT ON;
DECLARE @rowCounter INT;
BEGIN TRY
UPDATE
mbr_Messages
SET
fromDeleted = 1
WHERE
(fromMbrID = @fromMbrID) AND (toMbrID = @toMbrID) AND (fromDeleted = 0);
SET @rowCounter = @@ROWCOUNT;
UPDATE
mbr_Messages
SET
toDeleted = 1
WHERE
(fromMbrID = @toMbrID) AND (toMbrID = @fromMbrID) AND (toDeleted = 0);
SET @rowCounter = @rowCounter + @@ROWCOUNT;
END TRY
BEGIN CATCH
PRINT 'Update failed';
END CATCH
RETURN @rowCounter
END