在sql中使用回滚查询删除命令

问题描述 投票:0回答:2

我必须在生产数据库中运行删除和更新查询,并且 where 条件太复杂而无法应用。我已经创建了查询,但在执行之前我想测试这个查询。所以我想在应用实际删除查询之前回滚查询。如何做到这一点?

sql sql-server
2个回答
3
投票

使用

BEGIN
TRANS
启动事务,然后执行查询。

然后查看查询的结果,如果它们是您想要的,那么您可以提交事务,否则使用

ROLLBACK
命令将其回滚。

这是一个例子:

BEGIN TRAN t1 -- Begin the transaction

      DELETE * FROM Table_Name WHERE col=1  -- Do the "scary operation" in 
      --the production environment
      SELECT * FROM Table_Name -- Make sure it did what you thought it should 
      have.
      -- Then depending on results: 

COMMIT TRAN t1 -- Satisfied with results - Commits the transaction (delete 
operation)

ROLLBACK TRAN t1 -- Results not as expected - Rollback the transaction.

0
投票

不应该首选在生产数据库上执行此类操作,因为即使您创建事务并提交或回滚,它也会阻塞当时的所有其他进程,

So it is not preferred to create a transaction directly on prod DB
。您可以转储数据库并通过事务使用它。

SQL命令:

Begin TRAN
     Delete Query
     Select Query --to confirm
     
    Rollback --if result not expected
Commit --if expected result is found

如果删除查询按预期工作,则只需运行此查询,而不在产品数据库上使用事务。

© www.soinside.com 2019 - 2024. All rights reserved.