我的存储过程结构如下所示,我收到错误
关键字' BEGIN'附近的语法不正确。
如果我删除BEGIN TRAN
和COMMIT 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。请忽略查询逻辑。我尝试通过删除业务逻辑来简化代码。
答案 0 :(得分:6)
您无法在 CTE中间Map
,将交易移至CTE之外。
BEGIN TRAN
您也可以合法地将交易仅应用于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
不会包含在交易中。
UPDATE