1

我有一个存储过程构建更新查询,每次循环都存储在临时表中。

构建的总查询 UNKNOWN(2 到 4)

如何在事务中放置多个查询?

例如,临时表在EXPSQL( nvarchar)列中包含以下行

id   EXPSQL
1    Update tableA SET Name = 'Test' WHERE id=1
2    Update tableB SET Name = 'Test2' WHERE id=10

如何开始执行上述查询的循环事务?还是有其他方法?

while @id < total
begin
    set @id = @id +1
    select @SQL = EXPSQL FROM #TEMPTABLE WHERE id=@id
    EXEC (@SQL)
end

谢谢

4

1 回答 1

0

如果要全部执行:

begin transaction

while @id < total
begin
    set @id = @id +1
    select @SQL = EXPSQL FROM #TEMPTABLE WHERE id=@id
    EXEC (@SQL)

    -- if a error occurs go back to the original state
    if(@@error <> 0)
       rollback transaction
end

commit transaction

如果要单独执行每个:

while @id < total
begin
    set @id = @id +1
    select @SQL = EXPSQL FROM #TEMPTABLE WHERE id=@id

    begin transaction
    EXEC (@SQL)

    -- if a error occurs go back to the original state
    if(@@error <> 0)
       rollback transaction
    else
       commit transaction
end
于 2012-08-24T09:56:16.200 回答