问题:我有这个SQL脚本:
DECLARE @in_TE_UID varchar(36)
DECLARE @in_ZO_BETE_Sort int
DECLARE @in_user int
SET @in_TE_UID = '9f510440-8828-44ce-bbea-6bc866902262'
SET @in_ZO_BETE_Sort = 0
SET @in_user = 12435
-- http://stackoverflow.com/questions/884334/tsql-try-catch-transaction-in-trigger
BEGIN TRANSACTION BeforeUpdate;
BEGIN TRY
IF NOT EXISTS
(
SELECT 1 FROM T_FMS_ZO_Benutzer_TeaserOrder
WHERE (T_FMS_ZO_Benutzer_TeaserOrder.ZO_BETE_Status = 1)
AND (T_FMS_ZO_Benutzer_TeaserOrder.ZO_BETE_BE_ID = @in_user)
AND
(
T_FMS_ZO_Benutzer_TeaserOrder.ZO_BETE_TE_UID = @in_TE_UID
OR
(
@in_TE_UID IS NULL
AND
T_FMS_ZO_Benutzer_TeaserOrder.ZO_BETE_TE_UID IS NULL
)
)
)
BEGIN
INSERT INTO T_FMS_ZO_Benutzer_TeaserOrder
(
ZO_BETE_UID
,ZO_BETE_BE_ID
,ZO_BETE_TE_UID
,ZO_BETE_Sort
,ZO_BETE_Status
)
VALUES
(
NEWID() --<ZO_BETE_UID, uniqueidentifier,>
,@in_user --<ZO_BETE_BE_ID, int,>
,@in_TE_UID --<ZO_BETE_TE_UID, uniqueidentifier,>
,@in_ZO_BETE_Sort --<ZO_BETE_Sort, int,>
,1 --<ZO_BETE_Status, int,>
)
;
END
ELSE
BEGIN
UPDATE T_FMS_ZO_Benutzer_TeaserOrder
SET ZO_BETE_Sort = @in_ZO_BETE_Sort
WHERE (T_FMS_ZO_Benutzer_TeaserOrder.ZO_BETE_Status = 1)
AND (T_FMS_ZO_Benutzer_TeaserOrder.ZO_BETE_BE_ID = @in_user)
AND
(
T_FMS_ZO_Benutzer_TeaserOrder.ZO_BETE_TE_UID = @in_TE_UID
OR
(
@in_TE_UID IS NULL
AND
T_FMS_ZO_Benutzer_TeaserOrder.ZO_BETE_TE_UID IS NULL
)
)
;
END
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION BeforeUpdate --RollBack in case of Error
--RETURN
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;
SELECT
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
END CATCH
当我运行一次时运行正常。
如果之后我跑了
SELECT * FROM T_FMS_ZO_Benutzer_TeaserOrder
然后超时。
如果我添加with (nolock)
,那就可以了。
如果我查看SSMS中的进程,我会看到LCK_M_S
的锁定选择。
如果我在代码中执行相同的命令,我总是会收到此错误:
EXECUTE之后的事务计数表示BEGIN和COMMIT语句的数量不匹配。先前的计数= 0,当前计数= 1
真的,这段代码出了什么问题?
答案 0 :(得分:5)
您还没有在任何地方放置COMMIT
。据推测它应该在END TRY