T-SQL script to wait till status of snap agent is

2019-08-20 09:41发布

问题:

I'm trying to build a SQL script to wait till snapshot agent finish create snapshot (if it is in progress) before dropping the replication

Current status: We have some SQL scripts to disable replication (they are run as part of VSTS release pipelines). Sometimes, there might be a snapshot being generated. If replication is being disabled while a snapshot is in progress, script fails.

I'm using below script to check the status of snapshot agent

SELECT status FROM dbo.MSReplication_monitordata WHERE publication = 'PublicationName' and agent_type = 1) = 3

End goal:

I want help to achieve the following:

script check if snapshot agent if running or not. If it is running, it will wait till it is completed (snapshot generated), then do the action (drop replication).

I already have the scripts for dropping replication, what I need help about is the logic to handle this scenario.

Edit:

My question is not a duplicate from How to check replication snapshot agent status?

i need help with the logic to create a script to wait till snapshot agent is idle (if it is running). I don't know how to do it in t-sql.

I believe (waitfor) or (while) will help, but I don't know how to use them.

https://docs.microsoft.com/en-us/sql/t-sql/language-elements/waitfor-transact-sql?view=sql-server-2017 https://docs.microsoft.com/en-us/sql/t-sql/language-elements/while-transact-sql?view=sql-server-2017

回答1:

I was able to use while loop using below:

    use [distribution];
    declare @status int = 2

     select @status = status
     FROM dbo.MSReplication_monitordata
     WHERE publication = 'PublicationName' and agent_type = 1

     while @status = 3
     begin
     WAITFOR DELAY '00:00:03'
     select @status = status
     FROM dbo.MSReplication_monitordata
     WHERE publication = 'Publication.Name' and agent_type = 1
     end