2015-10-20 18 views
2

我有這個非常簡單的一段SQL,這是行爲不端,併爲我的生活找不到原因: 注:它實際上是存儲過程中,但它的這個簡化版本演示了問題區域。簡單的SQL是所有奇怪的(至少我知道)

declare @UserId int = 297; 
declare @Password [RSNAME] = 'somepassword99'; 

begin try 
if (@UserId > 0 and @Password <> '') 
    begin 
    update [User] 
     set [Password] = @Password 
    where UserId = @UserId; 
    print(@@rowcount); --just to track changes 
    end 
end try 
begin catch 
    raiserror ('Error updating password!', 16, 1); 
end catch; 

if (@@rowcount <> 1) 
begin 
    print(@@rowcount); --just to track changes 
    raiserror ('Error updating password! Zero or too many rows changed!', 16, 1); 
end 

在執行時,我得到這樣的結果:

(1行(S)的影響)

1(這是if條件裏面的行數)

0(這是在if條件之外的rowcount上)

消息50000,級別16,狀態1,行20

錯誤更新密碼!零或太多的行改變了!

如果我把「如果(@@ ROWCOUNT <> 1)」的開始閉鎖段內的部分,然後一切工作正常。修改表後,@@ rowcount似乎已重置?

+1

'@@ ROWCOUNT'由* *每次重置聲明。 –

回答

3

@@ROWCOUNT被每個語句重置。你需要存儲在@@rowcount可變幫手:

declare @UserId int = 297; 
declare @Password [RSNAME] = 'somepassword99'; 
declare @rowcount INT = 0; 

begin try 
if (@UserId > 0 and @Password <> '') 
    begin 
    update [User] 
     set [Password] = @Password 
    where UserId = @UserId; 

    select @rowcount = @@rowcount; 
    print(@rowcount); --just to track changes 
    end 
end try 
begin catch 
    raiserror ('Error updating password!', 16, 1); 
end catch; 

if (@rowcount <> 1) 
begin 
    print(@rowcount); --just to track changes 
    raiserror ('Error updating password! Zero or too many rows changed!', 16, 1); 
end 

簡單的演示:

SELECT 1 
UNION ALL 
SELECT 2; 

SELECT @@rowcount; -- 2 

SELECT @@rowcount; -- 1 

和:

SELECT 1 
UNION ALL 
SELECT 2; 

PRINT(@@rowcount); -- Print 2 

SELECT @@rowcount; -- 0 
相關問題