3
我需要從存儲過程中獲取受影響的記錄數。基於這個值,我想更新用戶動作是否完成。獲取交易記錄中插入的記錄數
但我的輸出@RecordsAffected
參數始終是0
如何讓沒有插入交易記錄?
其次How can I get the number of records affected by a stored procedure?和http://rusanu.com/2009/06/11/exception-handling-and-nested-transactions/
這是我的程序
ALTER PROCEDURE [dbo].[SaveRoleFeatures]
(
@RoleId INT,
@SelectedFeatures AS IdInt READONLY,
@RecordsAffected INT OUTPUT
)
AS
BEGIN
set nocount on;
DECLARE @ErrorCode int
SELECT @ErrorCode = @@ERROR
declare @trancount int;
set @trancount = @@trancount;
BEGIN TRY
BEGIN TRAN
DELETE FROM RoleXFeature WHERE RoleIid= @RoleId
INSERT RoleXFeature
(
RoleIid,
FeatureId,
IsDeleted
)
SELECT
@RoleId,
Id,
0
FROM @SelectedFeatures
COMMIT TRAN
SET @RecordsAffected = @@ROWCOUNT
END TRY
BEGIN CATCH
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(),
@message = ERROR_MESSAGE(), @xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction SaveRoleFeatures;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
return;
END CATCH
END
@ RecordsAffected = @@ ROWCOUNT'提交 – Blorgbeard
@Blorgbeard,是的它正在工作。謝謝。但是爲什麼在COMMIT之後它不工作?任何想法? – Billa
@Billa顯然是因爲@@ rowcount應該返回受最後一條語句影響的行數,而'commit'是一個語句[記錄](http://msdn.microsoft.com/en-us/ library/ms187316.aspx)將「@@ rowcount」設置爲0. – GSerg