2015年7月15日星期三

T-SQL : u_KillAllTasks

USE [ToolBox]
GO
/****** Object:  StoredProcedure [dbo].[u_KillAllTasks]    Script Date: 07/15/2015 15:39:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER 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='INPROUS, INPROEU, TOOLBOX'
END 

沒有留言:

發佈留言