【发布时间】:2014-08-17 20:31:36
【问题描述】:
我试图在 Else 语句中连续更新两个表。
因此,我将我的 Update 语句包装在一个事务中,我认为这是正确的方法,但在尝试执行此操作时出现以下错误。所有变量都在存储过程的开头声明。
我在这里错过了什么或做错了什么?
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'ELSE'.
Msg 137, Level 15, State 2, Line 4
Must declare the scalar variable "@parentID".
Msg 137, Level 15, State 2, Line 11
Must declare the scalar variable "@lastUpdate".
我的 SQL(更新:发布完整查询):
ALTER PROCEDURE [dbo].[MOC_UpdateNav]
@itemID int,
@parentID int,
@itemName nvarchar(100),
@linkRef nvarchar(2000),
@sortID int,
@lastUpdate nvarchar(50),
@modBy varchar(50)
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS
(
SELECT *
FROM MOC_Links
WHERE itemID = @itemID
)
INSERT INTO MOC_Links
(
parentID,
itemName,
linkRef,
sortID
)
SELECT @parentID,
@itemName,
@linkRef,
@sortID
INSERT INTO MOC_Log
(
lastUpdate,
modTime,
modBy
)
SELECT @lastUpdate,
GETDATE(),
@modBy
ELSE
BEGIN TRANSACTION
UPDATE MOC_Links
SET parentID = @parentID,
itemName = @itemName,
linkRef = @linkRef,
sortID = @sortID
WHERE itemID = @itemID
UPDATE MOC_Log
SET lastUpdate = @lastUpdate,
modTime = GETDATE(),
modBy = @modBy
WHERE itemID = @itemID
COMMIT
END
【问题讨论】:
-
begin transaction不会启动一个块,因此您需要将begin/end包裹在 else 块周围。 -
谢谢。那么我是否只需要在 Commit 下方添加一个 End 或在 Begin Transaction 上方添加另一个 Begin ?
标签: sql sql-server stored-procedures transactions sql-update