2015年7月31日星期五

TSQL - DBO.U_KillAllTasks

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[u_KillAllTasks]
( @Database nvarchar(200))
AS
BEGIN
    SET @Database = REPLACE (@Database, ' ','')
    SET @Database = ''''+REPLACE (@Database, ',',''',''')+''''
   
    DECLARE @SCRIPT NVARCHAR(MAX);
   
    DECLARE @spid INT;

    DECLARE MyCursor CURSOR FOR
    SELECT P.spid FROM SYS.sysprocesses P JOIN SYS.databases D ON P.dbid = D.database_id
    WHERE D.name NOT IN ('MASTER','MODEL','MSDB','TEMPDB') AND P.spid <> @@SPID
    --WHERE D.name IN (@Database)
   
    --PRINT @Database
   
    OPEN MyCursor;

    -- Perform the first fetch and store the values in variables.
    -- Note: The variables are in the same order as the columns
    -- in the SELECT statement.

    FETCH NEXT FROM MyCursor
    INTO @spid;

    -- Check @@FETCH_STATUS to see if there are any more rows to fetch.
    WHILE @@FETCH_STATUS = 0
    BEGIN

       -- Concatenate and display the current values in the variables.
       SET @SCRIPT = 'KILL '+ LTRIM(STR(@spid))
        PRINT @SCRIPT
        EXEC ( @SCRIPT )
       
       -- This is executed as long as the previous fetch succeeds.
       FETCH NEXT FROM MyCursor
       INTO @spid;
    END

    CLOSE MyCursor;
    DEALLOCATE MyCursor;

    ----------------------------------------------------------------
    -- EXEC DBO.U_KillAllTasks @DATABASE='DATABASE01,
DATABASE02,DATABASE03'
END

沒有留言:

發佈留言