我有一个stored procedure
,如果存在给定记录,则从表中删除记录。
CREATE PROCEDURE [dbo].[USP_DTEST]
@CfgKey AS VARCHAR(100)
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRAN
--Deletes ConfigSetting table if data exists
IF EXISTS
(
SELECT 1
FROM [dbo].[ConfigSetting]
WHERE CfgKey = @CfgKey
AND RowStatus = 'A'
)
BEGIN
DELETE
FROM [dbo].[ConfigSetting]
WHERE CfgKey = @CfgKey
AND RowStatus = 'A'
END
IF @@ERROR = 0
BEGIN
SELECT 'Number of Records Deleted : '+ CAST(@@rowcount AS varchar(10))
COMMIT TRAN;
END
END TRY
BEGIN CATCH
SELECT @@ERROR AS ERROR, ERROR_LINE() AS [Error Line], ERROR_MESSAGE() AS [Error Message]
ROLLBACK TRAN;
END CATCH
SET NOCOUNT OFF;
END
stored procedure
运行正常。但是当我执行sp @@rowcount
时总是返回0
。如果我将@@rowcount
置于error handling
块之上,则会返回1.为什么会这样?这个query
中是否有语法错误?
谢谢
答案 0 :(得分:4)
看看这个演示。您应该在删除后立即存储@@rowcount
。正如ZLK在他的评论中所说,@@rowcount
将被任何其他Sql语句重置,包括IF。
create table demo (n int);
insert demo(n) values (1), (2);
declare @rc int =-1;
delete from demo where n=1;
set @rc = @@rowcount;
if (@@error = 0) -- this will reset @@rowcount
select @rc, @@rowcount -- returns 1, 0