我不是来自SQL背景,所以我需要一个非常明确的答案。我每天都在.net中构建接口,有时使用简单的语句从SQL中提取数据。我之前从未与商店程序有任何关系。我们的开发人员(每月休假)和我们的DBA(因不可预见的未来而生病)都离开了,并且是唯一一个至少看过SQL Server的人,我最终取代了他们。我感到非常深刻,我的办公室里没有人问。我的老板在他成为老板之前曾经是一名SQL开发人员并且在今天坚持做技术工作时坚持认为这个存储过程存在问题并且我要修复它。我真的不知道怎么做。 C#非常容易......
这个(显然有缺陷的)存储过程旨在填充一个新字段 - Sequence。它意味着获取ClientID,然后更新该ClientID的用户记录。如果更新的记录数与预期的更新数不同,则该事务应该回滚。
我的老板声称这个程序写错了。你可以帮我解决一下,以便我能用我有限的SQL知识吗?
DECLARE @TargetRowCount INT
SELECT @TargetRowCount = COUNT(*)
FROM dbo.Users
WHERE ClientId = @ClientId
AND Sequence <> UPPER(Name)
BEGIN TRAN
UPDATE dbo.Users
SET Sequence = UPPER(Name)
SELECT COUNT(*)
FROM dbo.Users
WHERE ClientId = @ClientId
AND Sequence <> UPPER(Name)
IF(@@RowCount <> @TargetRowCount)
ROLLBACK TRAN
ELSE
COMMIT TRAN
提前谢谢!
答案 0 :(得分:0)
我很难理解该剧本的目的,但无论如何。 看到我包括的评论。希望它能帮到你:
DECLARE @TargetRowCount INT;
DECLARE @ChckRC1 INT;
DECLARE @ChckRC2 INT;
-- select how many rows with wrong name exist
SELECT @TargetRowCount = COUNT(*)
FROM dbo.Users
WHERE ClientId = @ClientId
AND Sequence <> UPPER(Name)
BEGIN TRAN
-- update users sequence, but really all?
UPDATE dbo.Users
SET Sequence = UPPER(Name)
-- i'd add the where clause from above
WHERE ClientId = @ClientId
AND Sequence <> UPPER(Name);
-- store how many rows the update hit
SET @ChckRC1 = @@ROWCOUNT;
-- select again how many rows with wrong name exist
SELECT @ChckRC2 = COUNT(*)
FROM dbo.Users
WHERE ClientId = @ClientId
AND Sequence <> UPPER(Name);
-- first count is different than actually updated rows,
-- some disappeared or new appeared.
IF (@ChckRC1 <> @TargetRowCount )
-- second count should be zero
-- any other value suggest, there is still a user with wrong sequence
OR (@ChckRC2 <> 0 )
ROLLBACK TRAN
ELSE
COMMIT TRAN
我不知道你为什么要检查计数3次。我要做的是:
-- update users sequence of some client with wrong sequence
UPDATE dbo.Users
SET Sequence = UPPER(Name)
WHERE ClientId = @ClientId
AND Sequence <> UPPER(Name);
return @@ROWCOUNT;