在包含更新语句和 CTE 的存储过程中使用 Begin tran

Use of Begin tran in a stored procedure which include update statements and a CTE

我的存储过程结构如下所示,但出现错误

Incorrect syntax near the keyword 'BEGIN'.

如果我删除 BEGIN TRANCOMMIT TRAN 语句,则存储过程运行良好。我不确定我做错了什么。任何人都可以帮助我了解哪里出了问题以及正确的方法应该是什么?

Create PROCEDURE proc_name(param1,param2,param3)
AS
Begin
with cte(col1, col2, col3)
AS
(
Select col1
,col2
,col3
from table1
)
Begin Tran
Update table2
set col1 = 'text'
from table2 inner join cte on cte.hmy = table2.hmy
where some condition

update table3
set date = ''
from table3 inner join cte on cte.hmy = table3.hmy
where some different condition

COMMIT TRAN

END

P.S。请忽略查询逻辑。我试图通过删除业务逻辑来简化代码。

您不能BEGIN TRAN CTE 中间,将事务移到 CTE 之外。

CREATE PROCEDURE proc_name(param1,param2,param3)
AS
BEGIN
  BEGIN TRAN

    ;WITH cte(col1, col2, col3)
    AS
    (
      SELECT col1
      ,col2
      ,col3
      FROM table1
    )
    UPDATE table2
    SET col1 = 'text'
    FROM table2 INNER JOIN cte ON cte.hmy = table2.hmy
    WHERE some condition

    UPDATE table3
    SET date = ''
    FROM table3 INNER JOIN cte ON cte.hmy = table3.hmy
    WHERE some different condition

  COMMIT TRAN
END

您也可以合法地将交易仅应用于 CTE,但第二个 UPDATE 不会包含在交易中。

CREATE PROCEDURE proc_name(param1,param2,param3)
AS
BEGIN
  BEGIN TRAN

    ;WITH cte(col1, col2, col3)
    AS
    (
      SELECT col1
      ,col2
      ,col3
      FROM table1
    )
    UPDATE table2
    SET col1 = 'text'
    FROM table2 INNER JOIN cte ON cte.hmy = table2.hmy
    WHERE some condition

  COMMIT TRAN

  -- UPDATE will run but not part of the transaction.
  UPDATE table3
  SET date = ''
  FROM table3 INNER JOIN cte ON cte.hmy = table3.hmy
  WHERE some different condition
END