简体   繁体   English

如何按顺序运行sql脚本?

[英]How to run sql scripts sequentially?

I have three actions to execute in one stored procedure.我要在一个存储过程中执行三个操作。 The issue is I need to make sure actions are executed if the previous action is completed.问题是我需要确保在上一个操作完成后执行操作。

For example: Action 2 must start execution after Action 1 is completed.例如: Action 2必须在Action 1完成后开始执行。

Please advise me on how to implement to get the above achieve.请告诉我如何实施以实现上述目标。

Codes:代码:

Action - 1行动 - 1

UPDATE Products 
SET MarkDownPrice = price + adjustment, 
    MarkDownDate = startdate, MarkedDown = 1
FROM Products p
JOIN PriceChanges pc ON p.SKU = pc.SKU and dateprocessed is null
WHERE pc.SKU = @SKU

Action - 2行动 - 2

UPDATE StyleColour 
SET isDirty = 1
FROM StyleColour sc
JOIN Products p ON sc.styleID = p.merretStyleID AND sc.Colour = p.MerretColour
WHERE SKU = @SKU

Action - 3行动 - 3

UPDATE pricechanges 
SET dateProcessed = getdate()
WHERE SKU = @SKU and dateprocessed is null

There are two ways in which you could do it.有两种方法可以做到。

  • Using @@error variable after each statement and checking it for non zero value (which i think is not the best way to do) which means error has occured so you just return from that pointing rolling back your tranaction.在每个语句之后使用 @@error 变量并检查它的非零值(我认为这不是最好的方法),这意味着发生了错误,因此您只需从该指向回滚您的事务。
  • Using Try catch.. something of sort:使用 Try catch .. 类似的东西:

     BEGIN TRY { sql_statement | statement_block } END TRY BEGIN CATCH { sql_statement | statement_block } END CATCH

    if you catch any error, just return from that point by rolling back the transaction.如果您发现任何错误,只需通过回滚事务从该点返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM