MS SQL Server StoreProc - Get Server Details

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 57

USE [master]

GO
/****** Object: StoredProcedure [dbo].[DCMON_ListAllBlocks] Script Date:
04/03/2012 23:13:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[DCMON_ListAllBlocks]

AS

--
--------------------------------------------------------------------
/*
=====================PURPOSE=========================

USING IN DC MONITORING PAGES, RETURNING ALL BLOCKS IN THE SQL SERVER


=====================OUTPUT==========================

=====================PAGE NAME(CALLING)==============

=====================CREATED BY/DATE ================


Jay
15/06/2007

*/
--------------------------------------------------------------------

SET NOCOUNT ON

DECLARE @DT DATETIME

SET @DT=GETDATE()
select @DT dt,@@servername as Servername,db_name(qs.dbid) as
Dbname,Program_name,hostname,
cpu,blocked,spid AS [Victim Process
ID],physical_Io,memusage,login_time,loginame
,text
From sys.sysprocesses
as qs with(nolock)
CROSS APPLY sys.dm_exec_sql_text( qs.sql_handle) as st
where spid in (select blocked
from sys.sysprocesses
as qs with(nolock)
where blocked>0
)

SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[s_SpaceUsed] Script Date: 04/03/2012
23:13:03 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[s_SpaceUsed]


@SourceDB VARCHAR(128)
as

---------------------------------------------------
/*
EXEC s_SpaceUsed 'itsalertgenerator'

=====================PURPOSE=========================
TO GET THE DETAILS OF SPACES THAT HAS BEEN USED
AND UNUSED BY TABLES FOR A SPECIFIED DATABASE

=====================OUTPUT==========================
NONE
INPUT PARAM:
@SourceDB VARCHAR(128)

=====================PAGE NAME(CALLING)==============
=====================CREATED BY/DATE ================
Jay
13-10-2006
*/
-----------------------------------------------------
SET NOCOUNT ON

DECLARE @sql VARCHAR(1000)

CREATE TABLE #TABLES(NAME VARCHAR(128))

SELECT @sql = 'INSERT #TABLES SELECT [TABLE_NAME] FROM ' + @SourceDB +


'.INFORMATION_SCHEMA.TABLES where TABLE_TYPE = ''BASE TABLE'''
EXEC (@sql)

CREATE TABLE #SpaceUsed


(
NAME VARCHAR(128),
rows VARCHAR(11),
reserved VARCHAR(18),
data VARCHAR(18),
index_size VARCHAR(18),
unused VARCHAR(18)
)
DECLARE @NAME VARCHAR(128)
SELECT @NAME = ''
WHILE EXISTS (SELECT * FROM #TABLES WHERE [NAME] > @NAME)
BEGIN
SELECT @NAME = MIN(NAME) FROM #TABLES WHERE NAME > @NAME
SELECT @sql = 'EXEC ' + @SourceDB + '..sp_EXECutesql N''INSERT
#SpaceUsed EXEC sp_spaceused [' + @NAME + ']'''
EXEC (@sql)
END
SELECT * FROM #SpaceUsed
DROP TABLE #TABLES
DROP TABLE #SpaceUsed
SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[sp_readerrorlog] Script Date: 04/03/2012
23:13:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROc [dbo].[sp_readerrorlog]
(
@p1 INT = 0,
@p2 INT = NULL,
@p3 VARCHAR(255) = NULL,
@p4 VARCHAR(255) = NULL)
AS
BEGIN

IF (NOT IS_SRVROLEMEMBER(N'securityadmin') = 1)
BEGIN
RAISERROR(15003,-1,-1, N'securityadmin')
RETURN (1)
END

IF (@p2 IS NULL)
EXEC master.sys.xp_readerrorlog @p1
ELSE
EXEC master.sys.xp_readerrorlog @p1,@p2,@p3,@p4
END

GO
/****** Object: StoredProcedure [dbo].[sp_SDS] Script Date: 04/03/2012 23:13:04
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_SDS]


@TargetDatabase sysname = NULL, -- NULL: all dbs
@Level varchar(10) = 'Database', -- or "File"
@UpdateUsage bit = 0, -- default no update
@Unit char(2) = 'MB' -- Megabytes, Kilobytes or Gigabytes
AS

/
***********************************************************************************
***************
**
**

** Created: Nov. 02, 2011


** Modified: Nov. 02, 2011
** usage: list db size AND path w/o SUMmary
** test code: sp_SDS -- default behavior
** sp_SDS 'maAster'
** sp_SDS NULL, NULL, 0
** sp_SDS NULL, 'file', 1, 'GB'
** sp_SDS 'Test_snapshot', 'Database', 1
** sp_SDS 'Test', 'File', 0, 'kb'
** sp_SDS 'pfaids', 'Database', 0, 'gb'
** sp_SDS 'tempdb', NULL, 1, 'kb'
**
***********************************************************************************
***************/

SET NOCOUNT ON;

IF @TargetDatabase IS NOT NULL AND DB_ID(@TargetDatabase) IS NULL


BEGIN
RAISERROR(15010, -1, -1, @TargetDatabase);
RETURN (-1)
END

IF OBJECT_ID('tempdb.dbo.##Tbl_CombinedInfo', 'U') IS NOT NULL


DROP TABLE dbo.##Tbl_CombinedInfo;

IF OBJECT_ID('tempdb.dbo.##Tbl_DbFileStats', 'U') IS NOT NULL


DROP TABLE dbo.##Tbl_DbFileStats;

IF OBJECT_ID('tempdb.dbo.##Tbl_ValidDbs', 'U') IS NOT NULL


DROP TABLE dbo.##Tbl_ValidDbs;

IF OBJECT_ID('tempdb.dbo.##Tbl_Logs', 'U') IS NOT NULL


DROP TABLE dbo.##Tbl_Logs;

CREATE TABLE dbo.##Tbl_CombinedInfo (


DatabaseName sysname NULL,
[type] VARCHAR(10) NULL,
LogicalName sysname NULL,
T dec(10, 2) NULL,
U dec(10, 2) NULL,
[U(%)] dec(5, 2) NULL,
F dec(10, 2) NULL,
[F(%)] dec(5, 2) NULL,
PhysicalName sysname NULL );

CREATE TABLE dbo.##Tbl_DbFileStats (


Id int identity,
DatabaseName sysname NULL,
FileId int NULL,
FileGroup int NULL,
TotalExtents bigint NULL,
UsedExtents bigint NULL,
Name sysname NULL,
FileName varchar(255) NULL );

CREATE TABLE dbo.##Tbl_ValidDbs (


Id int identity,
Dbname sysname NULL );
CREATE TABLE dbo.##Tbl_Logs (
DatabaseName sysname NULL,
LogSize dec (10, 2) NULL,
LogSpaceUsedPercent dec (5, 2) NULL,
Status int NULL );

DECLARE @Ver varchar(10),


@DatabaseName sysname,
@Ident_last int,
@String varchar(2000),
@BaseString varchar(2000);

SELECT @DatabaseName = '',


@Ident_last = 0,
@String = '',
@Ver = CASE WHEN @@VERSION LIKE '%9.0%' THEN 'SQL 2005'
WHEN @@VERSION LIKE '%8.0%' THEN 'SQL 2000'
WHEN @@VERSION LIKE '%10.0%' THEN 'SQL 2008'
END;

SELECT @BaseString =
' SELECT DB_NAME(), ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'CASE WHEN status & 0x40 = 0x40 THEN ''Log'' ELSE
''Data'' END'
ELSE ' CASE type WHEN 0 THEN ''Data'' WHEN 1 THEN ''Log'' WHEN 4 THEN ''Full-
text'' ELSE ''reserved'' END' END +
', name, ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'filename' ELSE 'physical_name' END +
', size*8.0/1024.0 FROM ' +
CASE WHEN @Ver = 'SQL 2000' THEN 'sysfiles' ELSE 'sys.database_files' END +
' WHERE '
+ CASE WHEN @Ver = 'SQL 2000' THEN ' HAS_DBACCESS(DB_NAME()) = 1' ELSE 'state_desc
= ''ONLINE''' END + '';

INSERT INTO dbo.##Tbl_ValidDbs SELECT name FROM


master.dbo.sysdatabases
ORDER BY name ASC ;

INSERT INTO dbo.##Tbl_Logs EXEC ('DBCC SQLPERF (LOGSPACE) WITH NO_INFOMSGS');

-- For data part


IF @TargetDatabase IS NOT NULL
BEGIN
SELECT @DatabaseName = @TargetDatabase;
IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName,'Status') = 'ONLINE'

AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'


BEGIN
SELECT @String = 'USE [' + @DatabaseName + '] DBCC UPDATEUSAGE (0)';
PRINT '*** ' + @String + ' *** ';
EXEC (@String);
PRINT '';
END

SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type,


LogicalName, PhysicalName, T) ' + @BaseString;
INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents,
UsedExtents, Name, FileName)
EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');
EXEC ('USE [' + @DatabaseName + '] ' + @String);

UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName;


END
ELSE
BEGIN
WHILE 1 = 1
BEGIN
SELECT TOP 1 @DatabaseName = Dbname FROM dbo.##Tbl_ValidDbs WHERE Dbname >
@DatabaseName ORDER BY Dbname ASC;
IF @@ROWCOUNT = 0
BREAK;
IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName, 'Status') =
'ONLINE'
AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <>
'READ_ONLY'
BEGIN
SELECT @String = 'DBCC UPDATEUSAGE (''' + @DatabaseName + ''') ';
PRINT '*** ' + @String + '*** ';
EXEC (@String);
PRINT '';
END

SELECT @Ident_last = ISNULL(MAX(Id), 0) FROM dbo.##Tbl_DbFileStats;

SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type,


LogicalName, PhysicalName, T) ' + @BaseString;

EXEC ('USE [' + @DatabaseName + '] ' + @String);

INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents,


UsedExtents, Name, FileName)
EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');

UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName WHERE Id


BETWEEN @Ident_last + 1 AND @@IDENTITY;
END
END

-- set used size for data files, do not change total obtained from
sys.database_files as it has for log files
UPDATE dbo.##Tbl_CombinedInfo
SET U = s.UsedExtents*8*8/1024.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_DbFileStats s
ON t.LogicalName = s.Name AND s.DatabaseName = t.DatabaseName;

-- set used size and % values for log files:


UPDATE dbo.##Tbl_CombinedInfo
SET [U(%)] = LogSpaceUsedPercent,
U = T * LogSpaceUsedPercent/100.0
FROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_Logs l
ON l.DatabaseName = t.DatabaseName
WHERE t.type = 'Log';

UPDATE dbo.##Tbl_CombinedInfo SET F = T - U, [U(%)] = U*100.0/T;


UPDATE dbo.##Tbl_CombinedInfo SET [F(%)] = F*100.0/T;

IF UPPER(ISNULL(@Level, 'DATABASE')) = 'FILE'


BEGIN
IF @Unit = 'KB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T * 1024, U = U * 1024, F = F * 1024;

IF @Unit = 'GB'
UPDATE dbo.##Tbl_CombinedInfo
SET T = T / 1024, U = U / 1024, F = F / 1024;

SELECT DatabaseName AS 'Database',


type AS 'Type',
LogicalName,
T AS 'Total',
U AS 'Used',
[U(%)] AS 'Used (%)',
F AS 'Free',
[F(%)] AS 'Free (%)',
PhysicalName
FROM dbo.##Tbl_CombinedInfo
WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%')
ORDER BY DatabaseName ASC, type ASC;

SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB'
END AS 'SUM',
SUM (T) AS 'TOTAL', SUM (U) AS 'USED', SUM (F) AS 'FREE' FROM
dbo.##Tbl_CombinedInfo;
END

IF UPPER(ISNULL(@Level, 'DATABASE')) = 'DATABASE'


BEGIN
DECLARE @Tbl_Final TABLE (
DatabaseName sysname NULL,
TOTAL dec (10, 2),
[=] char(1),
used dec (10, 2),
[used (%)] dec (5, 2),
[+] char(1),
free dec (10, 2),
[free (%)] dec (5, 2),
[==] char(2),
Data dec (10, 2),
Data_Used dec (10, 2),
[Data_Used (%)] dec (5, 2),
Data_Free dec (10, 2),
[Data_Free (%)] dec (5, 2),
[++] char(2),
Log dec (10, 2),
Log_Used dec (10, 2),
[Log_Used (%)] dec (5, 2),
Log_Free dec (10, 2),
[Log_Free (%)] dec (5, 2) );

INSERT INTO @Tbl_Final


SELECT x.DatabaseName,
x.Data + y.Log AS 'TOTAL',
'=' AS '=',
x.Data_Used + y.Log_Used AS 'U',
(x.Data_Used + y.Log_Used)*100.0 / (x.Data + y.Log) AS 'U(%)',
'+' AS '+',
x.Data_Free + y.Log_Free AS 'F',
(x.Data_Free + y.Log_Free)*100.0 / (x.Data + y.Log) AS 'F(%)',
'==' AS '==',
x.Data,
x.Data_Used,
x.Data_Used*100/x.Data AS 'D_U(%)',
x.Data_Free,
x.Data_Free*100/x.Data AS 'D_F(%)',
'++' AS '++',
y.Log,
y.Log_Used,
y.Log_Used*100/y.Log AS 'L_U(%)',
y.Log_Free,
y.Log_Free*100/y.Log AS 'L_F(%)'
FROM
( SELECT d.DatabaseName,
SUM(d.T) AS 'Data',
SUM(d.U) AS 'Data_Used',
SUM(d.F) AS 'Data_Free'
FROM dbo.##Tbl_CombinedInfo d WHERE d.type = 'Data' GROUP BY
d.DatabaseName ) AS x
JOIN
( SELECT l.DatabaseName,
SUM(l.T) AS 'Log',
SUM(l.U) AS 'Log_Used',
SUM(l.F) AS 'Log_Free'
FROM dbo.##Tbl_CombinedInfo l WHERE l.type = 'Log' GROUP BY
l.DatabaseName ) AS y
ON x.DatabaseName = y.DatabaseName;

IF @Unit = 'KB'
UPDATE @Tbl_Final SET TOTAL = TOTAL * 1024,
used = used * 1024,
free = free * 1024,
Data = Data * 1024,
Data_Used = Data_Used * 1024,
Data_Free = Data_Free * 1024,
Log = Log * 1024,
Log_Used = Log_Used * 1024,
Log_Free = Log_Free * 1024;

IF @Unit = 'GB'
UPDATE @Tbl_Final SET TOTAL = TOTAL / 1024,
used = used / 1024,
free = free / 1024,
Data = Data / 1024,
Data_Used = Data_Used / 1024,
Data_Free = Data_Free / 1024,
Log = Log / 1024,
Log_Used = Log_Used / 1024,
Log_Free = Log_Free / 1024;

DECLARE @GrantTotal dec(11, 2);


SELECT @GrantTotal = SUM(TOTAL) FROM @Tbl_Final;

SELECT
CONVERT(dec(10, 2), TOTAL*100.0/@GrantTotal) AS 'WEIGHT (%)',
DatabaseName AS 'DATABASE',
CONVERT(VARCHAR(12), used) + ' (' + CONVERT(VARCHAR(12), [used (%)]) + ' %)'
AS 'USED (%)',
[+],
CONVERT(VARCHAR(12), free) + ' (' + CONVERT(VARCHAR(12), [free (%)]) + ' %)'
AS 'FREE (%)',
[=],
TOTAL,
[=],
CONVERT(VARCHAR(12), Data) + ' (' + CONVERT(VARCHAR(12), Data_Used) + ', '
+
CONVERT(VARCHAR(12), [Data_Used (%)]) + '%)' AS 'DATA (used, %)',
[+],
CONVERT(VARCHAR(12), Log) + ' (' + CONVERT(VARCHAR(12), Log_Used) + ', ' +
CONVERT(VARCHAR(12), [Log_Used (%)]) + '%)' AS 'LOG (used, %)'
FROM @Tbl_Final
WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%')
ORDER BY DatabaseName ASC;

IF @TargetDatabase IS NULL
SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB'
END AS 'SUM',
SUM (used) AS 'USED',
SUM (free) AS 'FREE',
SUM (TOTAL) AS 'TOTAL',
SUM (Data) AS 'DATA',
SUM (Log) AS 'LOG'
FROM @Tbl_Final;
END

RETURN (0)

GO
/****** Object: StoredProcedure [dbo].[sp_SOS] Script Date: 04/03/2012 23:13:05
******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[sp_SOS]


@DbName sysname = NULL,
@SchemaName sysname = NULL,
@ObjectName sysname = N'%',
@TopClause nvarchar(20) = NULL,
@ObjectType nvarchar(50) = NULL,
@ShowInternalTable nvarchar(3) = NULL,
@OrderBy nvarchar(100) = NULL,
@UpdateUsage bit = 0
AS

/
*==================================================================================
===============

Author: Pritam Salvi


Created: Nov. 02, 2011

Modified: Nov. 02, 2011

Purpose: Manipulate object size calculation and display for SS 2000/2005/2008

Parameters:
@DbName: default is the current database
@SchemaName: default is null showing all schemas
@ObjectName: default is "%" including all objects in "LIKE" clause
@TopClause: default is null showing all objects. Can be "TOP N" or "TOP N
PERCENT"
@ObjectType: default is "S", "U", "V", "SQ" and "IT". All objects that can
be sized
@ShowInternalTable: default is "Yes", when listing IT, the Parent excludes it in
size
@OrderBy: default is by object name, can be any size related column
@UpdateUsage: default is 0, meaning "do not run DBCC UPDATEUSAGE"

Note: SS 2000/2005/2008 portable using dynamic SQL to bypass validation


error;
Use ISNULL to allow prefilled default parameter values;
Use "DBCC UPDATEUSAGE" with caution as it can hold up large databases;
Unicode compatible and case insensitive;

Sample codes:

EXEC dbo.sp_SOS;
EXEC dbo.sp_SOS 'AdventureWorks', NULL, '%', NULL, 'U', 'No', 'T', 1;
sp_SOS 'TRACE', NULL, NULL, Null, ' ,,, ,;SQ,; u ;;;,, v ,,;iT , ;',
'No', N'N', 0;
sp_SOS NULL, NULL, NULL, NULL, 'U', 'Yes', N'U', 1;
sp_SOS 'AdventureWorks', 'Person%', 'Contact%', NULL, 'U', 'no', 'N', 0;
sp_SOS 'AdventureWorks', NULL, NULL, N'Top 100 Percent', 'S', 'yes', N'N', 1;
sp_SOS 'AdventureWorks', NULL, 'xml_index_nodes_309576141_32000', NULL, 'IT',
'yes', 'N', 1;
sp_SOS 'TRACE', NULL, 'Vw_DARS_217_overnight_activity_11142007', ' top 10 ',
'v', 'yes', 'N', 0;
sp_SOS 'AdventureWorks', NULL, 'xml%', ' top 10 ', null, 'yes', 'N', 1;
sp_SOS 'AdventureWorks2008', NULL, 'sales%', NULL, ' ,,; u ;;;,, v ', 'No',
N'N', 1;
sp_SOS NULL, NULL, NULL, N'Top 100 Percent', ' ;;Q, U;V,', N'Y', 1;

===================================================================================
==============*/

SET NOCOUNT ON;

-- Input parameter validity checking


DECLARE @SELECT nvarchar(2500),
@WHERE_Schema nvarchar(200),
@WHERE_Object nvarchar(200),
@WHERE_Type nvarchar(200),
@WHERE_Final nvarchar(1000),
@ID int,
@Version nchar(2),
@String nvarchar(4000),
@Count bigint,
@GroupBy nvarchar(450);
IF ISNULL(@OrderBy, N'N') NOT IN (N'', N'N', N'R', N'T', N'U', N'I', N'D', N'F',
N'Y')
BEGIN
RAISERROR (N'Incorrect value for @OrderBy. Valid parameters are:
''N'' --> Listing by object name
''R'' --> Listing by number of records
''T'' --> Listing by total size
''U'' --> Listing by used portion (excluding free space)
''I'' --> Listing by index size
''D'' --> Listing by data size
''F'' --> Listing by unused (free) space
''Y'' --> Listing by object type ', 16, 1)
RETURN (-1)
END;

-- Object Type Validation and Clean up


DECLARE @OTV nvarchar(10), @OTC nvarchar(10);
SELECT @OTV =
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@ObjectType,

N'S, U, V, SQ, IT'), N' ', N''), N',', N''), N';', N''), N'SQ', N''),
N'U', N''),
N'V', N''), N'IT', N''), N'S', N'');
IF LEN(@OTV) <> 0 -- only allow comma, semi colon and space around S,U,V,SQ,IT
BEGIN
RAISERROR (N'Parameter error. Choose ''S'', ''U'', ''V'', ''SQ'', ''IT'' or any
combination of them,
separated by space, comma or semicolon.

S -> System table;


U -> User table;
V -> Indexed view;
SQ -> Service Queue;
IT -> Internal Table', 16, 1)
RETURN (-1)
END
ELSE -- passed validation
BEGIN
SET @OTC = UPPER(REPLACE(REPLACE(REPLACE(ISNULL(@ObjectType,N'S,U,V,SQ,IT'),N'
',N''),N',',N''),N';',N''))
SELECT @ObjectType =
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISN
ULL
(@ObjectType,
N'S,U,V,SQ,IT'),N',',N''),N';',N''),N'SQ',N'''QQ'''),N'IT',N'''IT'''),N'S',

N'''S'''),N'U',N'''U'''),N'V',N'''V'''),N'QQ',N'SQ'),N' ',N''),N'''''',N''',''')
END

---- common ----


SELECT @DbName = ISNULL(@DbName, DB_NAME()),
@Version = SUBSTRING(CONVERT(nchar(20), SERVERPROPERTY (N'ProductVersion')),
1,
CHARINDEX(N'.', CONVERT(nchar(20), SERVERPROPERTY
(N'ProductVersion')))-1),
@OrderBy = N'ORDER BY [' +
CASE ISNULL(@OrderBy, N'N')
WHEN N'N' THEN N'Object Name] ASC '
WHEN N'R' THEN N'Rows] DESC, [Object Name] ASC '
WHEN N'T' THEN N'Total(MB)] DESC, [Object Name] ASC '
WHEN N'U' THEN N'Used(MB)] DESC, [Object Name] ASC '
WHEN N'I' THEN N'Index(MB)] DESC, [Object Name] ASC '
WHEN N'D' THEN N'Data(MB)] DESC, [Object Name] ASC '
WHEN N'F' THEN N'Unused(MB)] DESC, [Object Name] ASC '
WHEN N'Y' THEN N'Type] ASC, [Object Name] ASC '
END;

---------------------- SS 2000 -----------------------------------


IF @Version = N'8'
BEGIN
SELECT @SELECT = N'USE ' + @DbName + N' SELECT ' + ISNULL(@TopClause, N' ') +

N''''' + USER_NAME(o.uid) + ''.'' + OBJECT_NAME(i.id) + '''' AS ''Object


Name'',
o.type AS ''Type'',
MAX(i.[rows]) AS ''Rows'',
CONVERT(dec(10,3), SUM(i.reserved * 8.000/1024)) AS ''Total(MB)'',
CONVERT(dec(10,3), SUM((i.reserved - i.used) * 8.000/1024)) AS ''Unused(MB)'',
CONVERT(dec(10,3), SUM(i.used * 8.000/1024)) AS ''Used(MB)'',
CONVERT(dec(10,3), SUM((i.used - CASE WHEN indid <> 255 THEN i.dpages ELSE
i.used END)
* 8.000/1024)) AS ''Index(MB)'',
CONVERT(dec(10,3), SUM(CASE WHEN indid <> 255 THEN i.dpages ELSE i.used END
* 8.000/1024)) AS ''Data(MB)''
FROM dbo.sysindexes i WITH (NOLOCK)
JOIN dbo.sysobjects o WITH (NOLOCK)
ON i.id = o.id
WHERE i.name NOT LIKE ''_WA_Sys_%''
AND i.indid IN (0, 1, 255) AND USER_NAME(o.uid) LIKE ''' + ISNULL(@SchemaName,
N'%') + N''' ',
-- SS 2000 calculation as below:
-- "reserved" = total size;
-- "dpages" = data used;
-- "used" = used portion (contains data and index);
-- text or image column: use "used" for data size
-- Nonclustered index take tiny space, somehow it is not counted (see
sp_spaceused).
@WHERE_Final = N' AND OBJECT_NAME(i.id) LIKE ''' + ISNULL(@ObjectName, N'%')
+ N''' AND o.type IN (' + @ObjectType + N') ',
@GroupBy = N' GROUP BY '''' + USER_NAME(o.uid) + ''.'' + OBJECT_NAME(i.id) +
'''', o.type ',
@String = @SELECT + @WHERE_Final + @GroupBy + @OrderBy
END

------------------- ss 2k5 ------------------------------------------------------


IF @Version IN (N'9', N'10')
BEGIN
SELECT @String = N'
IF OBJECT_ID (''tempdb.dbo.##BO'', ''U'') IS NOT NULL
DROP TABLE dbo.##BO

CREATE TABLE dbo.##BO (


ID int identity,
DOI bigint null, -- Daughter Object Id
DON sysname null, -- Daughter Object Name
DSI int null, -- Daughter Schema Id
DSN sysname null, -- Daughter Schema Name
DOT varchar(10) null, -- Daughter Object Type
DFN sysname null, -- Daughter Full Name
POI bigint null, -- Parent Object Id
PON sysname null, -- Parent Object Name
PSI bigint null, -- Parent Schema Id
PSN sysname null, -- Parent Schema Name
POT varchar(10) null, -- Parent Object Type
PFN sysname null -- Parent Full Name
)

INSERT INTO dbo.##BO (DOI, DSI, DOT, POI)


SELECT object_id, schema_id, type, Parent_object_id
FROM ' + @DbName + N'.sys.objects o WHERE type IN (''S'',''U'',''V'',''SQ'',''IT'')

USE ' + @DbName + N'


UPDATE dbo.##BO SET DON = object_name(DOI), DSN = schema_name(DSI), POI = CASE POI
WHEN 0 THEN DOI ELSE POI END
UPDATE dbo.##BO SET PSI = o.schema_id, POT = o.type FROM sys.objects o JOIN
dbo.##BO t ON o.object_id = t.POI
UPDATE dbo.##BO SET PON = object_name(POI), PSN = schema_name(PSI), DFN = DSN +
''.'' + DON,
PFN = schema_name(PSI)+ ''.'' + object_name(POI)
'
EXEC (@String)

SELECT
@WHERE_Type = CASE WHEN ISNULL(@ShowInternalTable, N'Yes') = N'Yes' THEN N't.DOT '
ELSE N't.POT ' END,
@SELECT = N'USE ' + @DbName + N'
SELECT ' + ISNULL(@TopClause, N'TOP 100 PERCENT ') +
N' CASE WHEN ''' + isnull(@ShowInternalTable, N'Yes') + N''' = ''Yes'' THEN
CASE t.DFN WHEN t.PFN THEN t.PFN
ELSE t.DFN + '' (''+ t.PFN + '')'' END ELSE t.PFN END AS ''Object Name'',

' + @WHERE_Type + N' AS ''Type'',


SUM (CASE WHEN ''' + isnull(@ShowInternalTable, N'Yes') + N''' = ''Yes''
THEN
CASE WHEN (ps.index_id < 2 ) THEN ps.row_count ELSE 0 END
ELSE CASE WHEN (ps.index_id < 2 and t.DON = t.PON) THEN ps.row_count
ELSE 0 END END) AS ''Rows'',
SUM (CASE WHEN t.DON NOT LIKE ''fulltext%'' OR t.DON LIKE
''fulltext_index_map%''
THEN ps.reserved_page_count ELSE 0 END)* 8.000/1024 AS
''Total(MB)'',
SUM (CASE WHEN t.DON NOT LIKE ''fulltext%'' OR t.DON LIKE
''fulltext_index_map%''
THEN ps.reserved_page_count ELSE 0 END
- CASE WHEN t.DON NOT LIKE ''fulltext%'' OR t.DON LIKE
''fulltext_index_map%'' THEN
ps.used_page_count ELSE 0 END)* 8.000/1024 AS ''Unused(MB)'',
SUM (CASE WHEN t.DON NOT LIKE ''fulltext%'' OR t.DON LIKE
''fulltext_index_map%''
THEN ps.used_page_count ELSE 0 END)* 8.000/1024 AS ''Used(MB)'',
SUM (CASE WHEN t.DON NOT LIKE ''fulltext%'' OR t.DON LIKE
''fulltext_index_map%''
THEN ps.used_page_count ELSE 0 END
- CASE WHEN t.POT NOT IN (''SQ'',''IT'') AND t.DOT IN (''IT'') and
''' + isnull(@ShowInternalTable, N'Yes')
+ N''' = ''No'' THEN 0 ELSE CASE WHEN (ps.index_id<2)
THEN
(ps.in_row_data_page_count+ps.lob_used_page_count+ps.row_overflow_used_page_count)
ELSE ps.lob_used_page_count + ps.row_overflow_used_page_count
END END) * 8.000/1024 AS ''Index(MB)'',
SUM (CASE WHEN t.POT NOT IN (''SQ'',''IT'') AND t.DOT IN (''IT'') and
''' + isnull(@ShowInternalTable, N'Yes')
+ N''' = ''No'' THEN 0 ELSE CASE WHEN (ps.index_id<2)
THEN
(ps.in_row_data_page_count+ps.lob_used_page_count+ps.row_overflow_used_page_count)
ELSE ps.lob_used_page_count + ps.row_overflow_used_page_count
END END) * 8.000/1024 AS ''Data(MB)''
FROM sys.dm_db_partition_stats ps INNER JOIN dbo.##BO t
ON ps.object_id = t.DOI
',
@ObjectType = CASE WHEN ISNULL(@ShowInternalTable, N'Yes') = N'Yes' THEN N'''IT'','
+ ISNULL(@ObjectType, N'''S'',''U'',
''V'', ''SQ'', ''IT''') ELSE ISNULL(@ObjectType, N'''S'', ''U'',
''V'', ''SQ'', ''IT''') END,
@WHERE_Schema = CASE WHEN ISNULL(@ShowInternalTable, N'Yes') = N'Yes' THEN N' t.DSN
' ELSE N' t.PSN ' END, -- DSN or PSN
@WHERE_Object = CASE WHEN ISNULL(@ShowInternalTable, N'Yes') = N'Yes' THEN N' t.DON
LIKE ''' + ISNULL(@ObjectName, N'%')
+ ''' OR t.PON LIKE ''' + ISNULL(@ObjectName, N'%') + N''' '
ELSE N' t.pon LIKE ''' + ISNULL(@ObjectName, N'%') + N''' ' END,
-- DON or PON
@WHERE_Final = N' WHERE (' + @WHERE_Schema + N' LIKE ''' + ISNULL(@SchemaName,
N'%') + N''' OR ' + @WHERE_Schema +
N' = ''sys'') AND (' + @WHERE_Object + N' ) AND ' + @WHERE_Type + N'
IN (' + @ObjectType + N') ',
@GroupBy = N'GROUP BY CASE WHEN ''' + ISNULL(@ShowInternalTable, N'Yes') + N''' =
''Yes'' THEN CASE t.DFN WHEN t.PFN
THEN t.PFN ELSE t.DFN + '' (''+ t.PFN + '')'' END ELSE t.PFN END, ' +
@WHERE_Type + N''
SELECT @String = @SELECT + @WHERE_Final + @GroupBy + @OrderBy
-- SELECT @String AS 'STRING'
END

----- common ------


IF OBJECT_ID(N'tempdb.dbo.##FO', N'U') IS NOT NULL
DROP TABLE dbo.##FO;

CREATE TABLE dbo.##FO (


ID int identity,
[Object Name] sysname,
[Type] varchar(2),
[Rows] bigint,
[Total(MB)] dec(10,3),
[-] nchar(1),
[Unused(MB)] dec(10,3),
[==] nchar(2),
[Used(MB)] dec(10,3),
[=] nchar(1),
[Index(MB)] dec(10,3),
[+] nchar(1),
[Data(MB)] dec(10,3) );

INSERT INTO dbo.##FO ([Object Name], [Type], [Rows], [Total(MB)],[Unused(MB)],


[Used(MB)],[Index(MB)],[Data(MB)])
EXEC (@String);
SELECT @Count = COUNT(*) FROM dbo.##FO;

IF @Count = 0
BEGIN
RAISERROR (N'No records were found macthcing your criteria.', 16, 1)
RETURN (-1)
END
ELSE -- There're at least one records
BEGIN
-- Run DBCC UPDATEUSAGE to correct wrong values
IF ISNULL(@UpdateUsage, 0) = 1
BEGIN
SELECT @ObjectName = N'', @ID = 0
WHILE 1 = 1
BEGIN
SELECT TOP 1 @ObjectName = CASE WHEN [Object Name] LIKE N'%
(%' THEN
SUBSTRING([Object Name], 1, CHARINDEX(N'(', [Object Name])-2)
ELSE [Object Name] END
, @ID = ID FROM dbo.##FO WHERE ID > @ID ORDER BY ID ASC
IF @@ROWCOUNT = 0
BREAK
PRINT N'==> DBCC UPDATEUSAGE (' + @DbName + N', ''' + @ObjectName +
N''') WITH COUNT_ROWS'
DBCC UPDATEUSAGE (@DbName, @ObjectName) WITH COUNT_ROWS
PRINT N''
END

PRINT N''
TRUNCATE TABLE dbo.##FO
INSERT INTO dbo.##FO ([Object Name], [Type], [Rows], [Total(MB)],
[Unused(MB)],
[Used(MB)],[Index(MB)],[Data(MB)]) EXEC (@String)
END
ELSE
PRINT N'(Warning: Run "DBCC UPDATEUSAGE" on suspicious objects. It may incur
overhead on big databases.)'
PRINT N''

UPDATE dbo.##FO SET [-] = N'-', [==] = N'==', [=] = N'=', [+] = N'+'

IF @Count = 1 -- when only 1 row, no need to sum up total


SELECT [Object Name], [Type], [Rows], [Total(MB)],[-], [Unused(MB)],[==],
[Used(MB)],[=],
[Index(MB)],[+],[Data(MB)]
FROM dbo.##FO ORDER BY ID ASC
ELSE
BEGIN
SELECT [Object Name], [Type], [Rows], [Total(MB)],[-], [Unused(MB)],[==],
[Used(MB)],[=],
[Index(MB)],[+],[Data(MB)]
FROM dbo.##FO ORDER BY ID ASC
COMPUTE SUM([Total(MB)]), SUM([Unused(MB)]), SUM([Used(MB)]),
SUM([Index(MB)]), SUM([Data(MB)])
END
END

RETURN (0)
GO
/****** Object: StoredProcedure [dbo].[sp_who3] Script Date: 04/03/2012
23:13:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_who3]
(
@SessionID int = NULL
)
AS
BEGIN
SELECT
SPID = er.session_id
,Status = ses.status
,[Login] = ses.login_name
,Host = ses.host_name
,BlkBy = er.blocking_session_id
,DBName = DB_Name(er.database_id)
,CommandType = er.command
,SQLStatement =
SUBSTRING
(
qt.text,
er.statement_start_offset/2,
(CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(nvarchar(MAX), qt.text)) * 2
ELSE er.statement_end_offset
END - er.statement_start_offset)/2
)
,ObjectName = OBJECT_SCHEMA_NAME(qt.objectid,dbid) + '.' +
OBJECT_NAME(qt.objectid, qt.dbid)
,ElapsedMS = er.total_elapsed_time
,CPUTime = er.cpu_time
,IOReads = er.logical_reads + er.reads
,IOWrites = er.writes
,LastWaitType = er.last_wait_type
,StartTime = er.start_time
,Protocol = con.net_transport
,transaction_isolation =
CASE ses.transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'Read Uncommitted'
WHEN 2 THEN 'Read Committed'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot'
END
,ConnectionWrites = con.num_writes
,ConnectionReads = con.num_reads
,ClientAddress = con.client_net_address
,Authentication = con.auth_scheme
FROM sys.dm_exec_requests er
LEFT JOIN sys.dm_exec_sessions ses
ON ses.session_id = er.session_id
LEFT JOIN sys.dm_exec_connections con
ON con.session_id = ses.session_id
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle) as qt
WHERE @SessionID IS NULL OR er.session_id = @SessionID
AND er.session_id > 50
ORDER BY
er.blocking_session_id DESC
,er.session_id

END

GO
/****** Object: StoredProcedure [dbo].[sp_WhoIsActive] Script Date: 04/03/2012
23:13:06 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[sp_WhoIsActive] AS SELECT 'stub version, to be replaced'
GO
/****** Object: StoredProcedure [dbo].[USP_ActiveTrans_OS_PRFCNR] Script Date:
04/03/2012 23:13:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROC [dbo].[USP_ActiveTrans_OS_PRFCNR]


AS
--------------------------------------------------------------------
/*
=====================PURPOSE=========================
TO FETCH DATA FROM sys.dm_os_performance_counters
=====================PARAMS==========================

=====================PAGE NAME(CALLING)==============
=====================CREATED BY/DATE ================
SALMAN
27/05/2008
=====================================================
*/
--------------------------------------------------------------------
SET NOCOUNT ON

BEGIN

SELECT 'SQLServer' as [object_name],'Transactions/sec' as


counter_name ,
count(*)as cntr_value,'' as [cntr_type]
FROM sys.sysprocesses WITH(NOLOCK)

END

SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[USP_AgentStatus] Script Date: 04/03/2012
23:13:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[USP_AgentStatus]


AS
--------------------------------------------------------------------
/*
===========================PURPOSE============================
To get the Agent Status
============================OUTPUT=============================

========================PAGE NAME(CALLING)=====================
=========================CREATED BY/DATE ======================

*/
--------------------------------------------------------------------
SET NOCOUNT ON

exec master..xp_servicecontrol 'QUERYSTATE', SQLSERVERAGENT

SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[USP_CPUUsage] Script Date: 04/03/2012
23:13:07 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[USP_CPUUsage]


AS
--------------------------------------------------------------------
/*
===========================PURPOSE============================
To get the CPU usage
============================OUTPUT=============================

========================PAGE NAME(CALLING)=====================
=========================CREATED BY/DATE ======================

*/
--------------------------------------------------------------------
SET NOCOUNT ON

DECLARE @ts_now BIGINT

SELECT @ts_now = cpu_ticks / CONVERT(FLOAT, cpu_ticks_in_ms) FROM


sys.dm_os_sys_info with(nolock)

SELECT top 1 @@servername as ServerName,


SQLProcessUtilization,

100 - SystemIdle - SQLProcessUtilization AS OtherProcessUtilization


FROM (
SELECT
record.value('(./Record/@id)[1]', 'int') AS record_id,

record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]',
'int') AS SystemIdle,

record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]',
'int') AS SQLProcessUtilization,
TIMESTAMP
FROM ( SELECT TIMESTAMP, CONVERT(XML, record) AS record
FROM sys.dm_os_ring_buffers with(nolock)
WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
AND record LIKE '% %') AS x
) AS y
ORDER BY record_id DESC

SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[USP_DbHostCount] Script Date: 04/03/2012
23:13:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[USP_DbHostCount]

as

--==========================PAGE NAME(CALLING)=======================
--==========================CREATED BY/DATE =========================
--Binod
--24/5/2008
--===================================================================
select hostname,count(spid) as "Total Srv Pro",db_name(qs.dbid) as
"DBName",@@servername as "Server"
from sys.sysprocesses as qs

group by hostname, qs.dbid

SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[USP_DiskStatus] Script Date: 04/03/2012
23:13:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[USP_DiskStatus]


AS
--------------------------------------------------------------------
/*
===========================PURPOSE============================
To get the disk space of server
============================OUTPUT=============================

========================PAGE NAME(CALLING)=====================
=========================CREATED BY/DATE ======================

*/
--------------------------------------------------------------------
SET NOCOUNT ON

DECLARE @tbl_Drive TABLE (id INT IDENTITY(1,1), Drive


VARCHAR(50),Free_space NUMERIC(18,4),Total_Space NUMERIC(18,4))
DECLARE @cnt INT, @lmt INT, @drive VARCHAR(50), @val NUMERIC(18,4)

INSERT INTO @tbl_Drive (Drive ,Free_space)


EXEC xp_fixeddrives

SELECT @lmt = MAX(id) FROM @tbl_Drive

SET @cnt = 1

WHILE @cnt <= @lmt


BEGIN
SELECT @drive = 'fsutil volume diskfree '+Drive+':' FROM @tbl_Drive
WHERE ID = @cnt

DECLARE @tbl_CMDSHELL TABLE (val varchar(150) )

--INSERT INTO @tbl_CMDSHELL (val)


--EXEC XP_CMDSHELL @drive

SELECT @val = CAST(LTRIM(RTRIM(SUBSTRING(val,CHARINDEX(':',val)


+1,LEN(val)))) AS NUMERIC(18,4)) FROM @tbl_CMDSHELL WHERE val LIKE 'total # of
bytes%'
SELECT @val = @val/1024/1024/1024

UPDATE @tbl_Drive SET Total_Space = @val WHERE id = @cnt


DELETE FROM @tbl_CMDSHELL

SET @cnt = @cnt+1

END
SELECT @@SERVERNAME SVRName,Drive,Total_Space AS Total_Space_GB,
(Free_space)/1024 Free_space_GB,GETDATE() Dt FROM @tbl_Drive

SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[usp_get_db_files_near_maxsize] Script
Date: 04/03/2012 23:13:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[usp_get_db_files_near_maxsize] (@nearMaxSizePct DECIMAL
(5,1) = 10.0)
AS
BEGIN
SET NOCOUNT ON

CREATE TABLE ##ALL_DB_Files (


dbname SYSNAME,
fileid smallint,
groupid smallint,
[size] INT NOT NULL,
[maxsize] INT NOT NULL,
growth INT NOT NULL,
status INT,
perf INT,
[name] SYSNAME NOT NULL,
[filename] NVARCHAR(260) NOT NULL)

-- loop over all databases and collect the information from sysfiles
-- to the ALL_DB_Files tables using the sp_MsForEachDB system procedure
EXEC sp_MsForEachDB
@command1='use [$];Insert into ##ALL_DB_Files select db_name(), * from sysfiles',
@replacechar = '$'

-- output the results


SELECT
[dbname] AS DatabaseName,
[name] AS dbFileLogicalName,
[filename] AS dbFilePhysicalFilePath,
ROUND(size * CONVERT(FLOAT,8) / 1024,0) AS ActualSizeMB,
ROUND(maxsize * CONVERT(FLOAT,8) / 1024,0) AS MaxRestrictedSizeMB,
ROUND(maxsize * CONVERT(FLOAT,8) / 1024,0) - ROUND(size * CONVERT(FLOAT,8) /
1024,0) AS SpaceLeftMB
FROM ##ALL_DB_Files
WHERE maxsize > -1 AND -- skip db files that have no max size
([maxsize] - [size]) * 1.0 < 0.01 * @nearMaxSizePct * [maxsize] -- find db files
within percentage
ORDER BY 6

DROP TABLE ##ALL_DB_Files

SET NOCOUNT OFF


END
GO
/****** Object: StoredProcedure [dbo].[USP_MC_MCT_ColoTrfStatus] Script Date:
04/03/2012 23:13:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create proc [dbo].[USP_MC_MCT_ColoTrfStatus]
AS
/*
EXEC [USP_MC_MCT_ColoTrfStatus]
=====================PURPOSE=========================
to Get Pairwise Transefer Status for MCT
Where No Transfer is Received in Last One Hour
=====================OUTPUT==========================
RecordSet
=====================PAGE NAME(CALLING)==============
ASCP Exe
=====================CREATED BY/DATE ================
Brinal 12/nov/2010
------------------------------------------------------
=====================Modified BY/DATE ================
Hitesh R
may 26 2011
uncommented the part MC_MCTAscpEnDisStatus
*/
BEGIN
SET NOCOUNT ON
SELECT TL.Autoid,X.*
FROM (

SELECT rel.MCTID MCTRegid, G.mcGUID ServerGUID, G.MCID


ServerRegid ,isnull( MN.DomainSSORegid,0) SSOREgid ,G.Coloid , ColoHost, Lungpath ,
CASE WHEN B.REGID IS NOT NULL THEN 'MCT LEVEL'
WHEN A.REGID IS Not NULL THEN 'MCT LEVEL'
WHEN BKP.MCTID IS NULL THEN 'MCT LEVEL'
WHEN isnull(Stoptfr,0)=1 Then 'MCT LEVEL'
WHEN isnull(Ch.RunStatus,'')='Failed'
Then 'MCT LEVEL'
WHEN isnull(MD.Colomaint,0) =1 Then 'COLO
LEVEL'
WHEN CH.RunStatus='SUCCESS' and
CH.TotalFilesQueuedForAllServers='0' THEN 'MCT LEVEL'
WHEN ISNULL(CHP.NCount,0) = 0 THEN 'MCT
LEVEL'
WHEN
Datediff(mi,ISNULL(Och.Dcdtime,'1/1/1900'),getdate())>60 AND dis.MCTID IS NOT NULL
THEN 'MCT LEVEL'
When
Datediff(mi,ISNULL(OS.LastDctime,'1/1/1900'),getdate())>60 THEN 'MCT LEVEL'
--COLO BASE ERROR HERE ONLY
WHEN ISNULL(T1.ErrLevel,1) = 2 AND
ISNULL(P.ErrLevel,2) = 2 Then 'COLO LEVEL'
Else 'MCT LEVEL'
END RootCause ,
Case WHEN B.REGID IS NOT NULL THEN 'Device Down
ticket'
WHEN A.REGID IS Not NULL THEN 'Tunnel
Down ticket'
WHEN BKP.MCTID IS NULL THEN 'Mirroring
Not Initiated'
WHEN Stoptfr = 1 Then 'Transfer Stopped
By NOC'
WHEN Ch.RunStatus='Failed' Then 'XML
Failed'
WHEN MD.Colomaint=1 Then 'Under
Maintenance'
WHEN CH.RunStatus='SUCCESS' AND
CH.TotalFilesQueuedForAllServers='0' THEN 'Nodes 0 in XML'
WHEN ISNULL(CHP.NCount,0) = 0 THEN
'Nodes 0 in XML'
WHEN
Datediff(mi,ISNULL(Och.Dcdtime,'1/1/1900'),getdate())>60 AND dis.MCTID IS NOT NULL
Then 'Transfer Pause by Client'
When
Datediff(mi,ISNULL(OS.LastDctime,'1/1/1900'),getdate())>60 AND
CH.RunStatus='SUCCESS' and CH.TotalFilesQueuedForAllServers > '0' THEN 'No status
from MCT (More Than 2 Hours)'
When T1.Errst IS NOT NULL THEN T1.ERRST

ELSE 'Others'
END Reason
,ISNULL([desc],'') Errstring
,O.Dcupdtime
FROM SMCRegIDattribute MN WITH(NOLOCK)
INNER JOIN MC_GuidColoRel G WITH(Nolock) ON
MN.SSORegid=G.MCID AND mn.GUID=G.mcGUID and ResType=1
INNER JOIN MstRegidMCMCTRel REL WITH(nOLOCK) ON
REL.MCID=G.MCID AND REL.MCGUID=G.MCGUID
INNER JOIN MSTCOLODRV MD with(nolock) On
MD.Coloid=G.coloid
LEFT JOIN MC_MCTAscpOffsiteHealthCheck OCh
with(nolock) On OCh.MCTID=rel.MCTID
LEFT JOIN ( Select
O.MCTID,ISNULL(L.ServerGuid,O.ServerGuid) mcGUID,ISNULL(L.ErrorDesc,[Desc])
[Desc],O.Dcupdtime
From McAscpTfrOffsite O
with(nolock)
LEFT JOIN MCAscpTrfStatus L
with(nolock) ON L.MCTID=O.MCTID AND O.ServerGuid=L.ServerGuid
WHERE DCupdtime=(SELECT
ISNULL(O2.DT,O1.Dt)
FROM
( Select MCTID ,ServerGUID,max(dcupdtime) Dt

From McAscpTfrOffsite with(nolock)

Group by MCTID,ServerGUID
)
O1
LEFT JOIN (
Select MCTID ,ServerGUID,max(dcupdtime) Dt

From McAscpTfrOffsite with(nolock)

WHERE Jobstatus='Failed' AND Datediff(Mi,Dcupdtime,GetDate())<=120


Group by MCTID,ServerGUID

) O2 On O2.MCTID=O1.MCTID and O2.ServerGUID=O1.ServerGUID


WHERE
O1.MCTID=O.MCTID and O1.ServerGUID=O.ServerGUID
)
) O On O.MCTID=rel.MCTID and
O.mcGUID=G.mcGUID

LEFT JOIN MC_MCTAscpEnDisStatus dis with(nolock) on


dis.MCTID=rel.MCTID and dis.sstate='Pause Offsite Transfer'

LEFT JOIN ( SELECT DISTINCT rel.MCTID


from MC_QALookup b With(NoLock)
INNER JOIN MstRegidMCMCTRel REL
WITH(NOLOCK) ON REL.MCID=B.MCID
WHERE
MCTLastAppConsistant>DATEADD(d,-3,getdate())
) BKP On Bkp.MCTID=REL.MCTID

LEFT JOIN MC_ExeToCreateReplicationFileXML ch


with(nolock) on ch.MCTID=rel.MCTID and CH.ServerGUID=MN.GUID
LEFT JOIN ( SELECT
ch.MCTID,SUM(CONVERT(BIGINT,FilesBeenQueued))Ncount
FROM
MC_ExeToCreateReplicationFileXML ch with(nolock)

Inner Join MC_GuidColoRel G With(nolock)


On CH.ServerGUID=G.MCGUID AND StopTFR=0 -- and UnderMaint=0
group by ch.MCTID
)chp on chp.MCTID=rel.MCTID
LEFT JOIN [30sec_alrtcons] b with(nolock) on
rel.MCTRegid=b.regid and ThresholdCounter in('BDRALIVE','30SECALIVE') --and
Isnull(ThresholdCounter,'')<>'AGENTMALFUNCTION'
LEFT JOIN HTTPSTunnel_AlrtCons A with(nolock) on
rel.MCTRegid=A.regid
LEFT JOIN( select a.MCTID
from MCAscpTrfStatus a with(nolock)
where
datediff(hh,a.LastTransferDate,getdate())< = 1

) t on T.MCTID=rel.MCTID

LEFT JOIN MCAscpTrfStatus OS with(nolock) On


OS.MCTId=rel.MCTID
LEFT JOIN MC_Asperatrferrors T1 With(Nolock) On
Charindex(T1.Errst,[desc])> 0
LEFT JOIN ( SELECT A.Coloid,Errst,Ratio,CASE WHEN
round((B.FNS*100)/A.NS,0)>Ratio Then 2 ELse 1 END ErrLevel
FROM( select
G.Coloid,Count(Distinct a.ServerGUID) NS
from McAscpTfrOffsite a
with(nolock)
Inner Join
MC_GuidColoRel G with(NoLock) On G.MCGUID=a.ServerGUID

where
datediff(Mi,a.Dcupdtime,getdate())<=60
Group By G.Coloid
) A
Inner join
( select
G.Coloid,Errst,ratio,Count(Distinct a.MCTID) FNS
from McAscpTfrOffsite a
with(nolock)
Inner Join
MC_GuidColoRel G with(NoLock) On G.MCGUID=a.ServerGUID
Inner join
MC_AsperaTrfErrors Er with(Nolock) On charindex(errst,[desc])>0
where
datediff(Mi,a.Dcupdtime,getdate())<=60
Group By
G.Coloid,Errst,ratio
) B On A.Coloid=B.COLOID

) P On G.Coloid=P.Coloid And
T1.Errst=P.Errst
WHERE T.MCTID IS NULL
)X
LEFT JOIN MC_MCTColoTrfLookup TL With(Nolock) On
TL.MCGuid=X.ServerGuid AND TL.MCTID=X.MCTRegID

SET NOCOUNT OFF


END

GO
/****** Object: StoredProcedure [dbo].[USP_MemoryUsage] Script Date: 04/03/2012
23:13:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[USP_MemoryUsage]


AS
--------------------------------------------------------------------
/*
===========================PURPOSE============================
To get the Memory usage
============================OUTPUT=============================

========================PAGE NAME(CALLING)=====================
=========================CREATED BY/DATE ======================

*/
--------------------------------------------------------------------
SET NOCOUNT ON

select top 1
x.value('(//TotalPhysicalMemory)[1]','int') as
[TotalPhysicalMemory],
x.value('(//AvailablePhysicalMemory)[1]','int')as
[AvailablePhysicalMemory],
x.value('(//Record/@time)[1]', 'bigint') as [TimeStamp]
from
(select cast(record as xml) as record
from sys.dm_os_ring_buffers WITH(NOLOCK)
where ring_buffer_type = N'RING_BUFFER_RESOURCE_MONITOR')
as r(x)
order by
[TimeStamp] desc

SET NOCOUNT OFF


GO
/****** Object: StoredProcedure [dbo].[USP_MSO_WeekWiseAgentRevenue] Script
Date: 04/03/2012 23:13:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create Procedure [dbo].[USP_MSO_WeekWiseAgentRevenue]
@InMonth BigInt,
@InYear BigInt,
@InCurrency VarChar(50),
@InTamID BigInt=Null,
@InBillingRequired Bit
--------------------------------------------------------------
/*
EXEC [USP_MSO_WeekWiseAgentRevenue] 10,2011,'usdollar',Null,1
=====================PURPOSE=================================
To Display the Revenue As on Last Day of a Week for
The Current Month
=====================PAGE NAME(CALLING)======================
Rep_RevenueProjection_CurrentMonth.asp
=====================CREATED BY/DATE ========================
Manoj T
18-Nov-2011
=====================MODIFIED BY/DATE ======================
Manoj T
07-Dec-2011
Added Criteria @InCurrency,@InTamID AND @InBillingRequired
*/
-------------------------------------------------------------
As

SET NOCOUNT ON

Declare @I BigInt,@J Numeric(18,2)


Select @I=0,@J=0

Declare @MemberList Table


(
MemberID BigInt,
BCurrency VarChar(50),
BillingRequired Bit
)

Insert Into @MemberList


(MemberID,BCurrency,BillingRequired)
Select MM.MemberID,MM.BCurrency,MM.BillingRequired
From GlobalConfig_Member MM With (NoLock)
Inner Join MgmtMemberDetails MD With (NoLock) ON MM.Memberid=MD.MemberID AND
MD.TamID=ISNULL(@InTamID,MD.TamID)
Where MM.BCurrency=IsNull(@InCurrency,MM.BCurrency) AND
BillingRequired=ISNULL(@InBillingRequired,BillingRequired)
AND MM.Memberid>@I

If @InTamID IS NULL
Begin
Insert Into @MemberList
(MemberID,BCurrency,BillingRequired)
Select MM.MemberID,MM.BCurrency,MM.BillingRequired
From GlobalConfig_Member MM With (NoLock)
Left Join @MemberList ML ON MM.MemberID=ML.MemberID
Where ML.MemberID Is Null AND
MM.BCurrency=IsNull(@InCurrency,MM.BCurrency)
AND
MM.BillingRequired=ISNULL(@InBillingRequired,MM.BillingRequired) AND MM.Memberid>@I
End

Select 'W'+Cast(B.WeekRange As CHAR(1))+' ('+Cast(Min(B.FromDate) As CHAR(2))


+'-'+Cast(Min(B.ToDate) As CHAR(2))+')' WeekRange,
B.BillingRequired,B.BCurrency,
Round(Sum(Case When ServiceId=1 Then AMT Else 0 End),2) [Base Desktop
Product (Desktop/Laptop)],
Round(Sum(Case When ServiceId=2 Then AMT Else 0 End),2) [Total Desktop
Care + (Base Desktop Product)],
Round(Sum(Case When ServiceId=3 Then AMT Else 0 End),2) [Total Desktop
Care + Service Tickets],
Round(Sum(Case When ServiceId=7 Then AMT Else 0 End),2) [Total Desktop
Care + (Help Desk)],
Round(Sum(Case When ServiceId=11 Then AMT Else 0 End),2) [Total Desktop
Care Plus],
Round(Sum(Case When ServiceId=4 Then AMT Else 0 End),2) [Base Server
Product],
Round(Sum(Case When ServiceId=5 Then AMT Else 0 End),2) [Server Watch +
(Base Server Product)],
Round(Sum(Case When ServiceId=6 Then AMT Else 0 End),2) [Remote Server
Care + (Base Server Product)],
Round(Sum(Case When ServiceId=8 Then AMT Else 0 End),2) [Proactive
Server Care],
Round(IsNull(Min(D.Amount),0),2) [AVAmount]
From
(
Select BillingRequired,WeekRange,BCurrency,Min(FromDate)
FromDate,Min(ToDate) ToDate,ServiceId,SUM(a.AMT) AMT
From(
--Select Case When BillingRequired Is Null Then 0 Else
BillingRequired End BillingRequired,GM.BCurrency,
Select GM.BillingRequired,GM.BCurrency,
DateAdd(d,0,DateDiff(d,0,Dateason))
DateAsOn,ServiceId,MS.AMT,WeekRange,MW.FromDate,MW.Todate
From MSO_SitewiseSlab_Sitewise_Daily_Consol MS
WITH(NOLOCK)
Inner Join @MemberList GM ON
MS.MEMBERID=GM.Memberid
Left Join MSO_Weekly_Slab MW
WITH(NOLOCK) On Day(MS.DateAson) BETWEEN MW.FromDate AND MW.Todate
Where MONTH(DateAsOn)=@InMonth AND YEAR(DateAsOn)=@InYear
AND MS.AMT >@J AND SiteID>@I --AND MS.MemberID >@I

)A
Group By BCurrency,BillingRequired,WeekRange,ServiceId
)B
Left Join
(
Select BillingRequired,WeekRange,BCurrency,Min(FromDate)
FromDate,Min(ToDate) ToDate,SUM(C.Amount) Amount
FROM
(
Select BillingRequired,WeekRange,BCurrency,Min(FromDate)
FromDate,Min(ToDate) ToDate,SUM(a.Amount) Amount
From(
--Select Case When BillingRequired Is Null Then 0
Else BillingRequired End BillingRequired,GM.BCurrency,
Select GM.BillingRequired,GM.BCurrency,
DateAdd(d,0,DateDiff(d,0,Dateason))
DateAsOn,MS.Amount,WeekRange,MW.FromDate,MW.Todate
From AV_MemberPoolWise_Daily_Consol MS WITH(NOLOCK)
Inner Join @MemberList GM ON
MS.MEMBERID=GM.Memberid
Left Join MSO_Weekly_Slab MW
WITH(NOLOCK) On Day(MS.DateAson) BETWEEN MW.FromDate AND MW.Todate
Where MONTH(DateAsOn)=@InMonth AND
YEAR(DateAsOn)=@InYear
)A
Group By BCurrency,BillingRequired,WeekRange

UNION ALL

Select BillingRequired,WeekRange,BCurrency,Min(FromDate)
FromDate,Min(ToDate) ToDate,SUM(a.Amount) Amount
From(
Select GM.BillingRequired,GM.BCurrency,
--Select Case When BillingRequired Is Null Then 0
Else BillingRequired End BillingRequired,GM.BCurrency,
DateAdd(d,0,DateDiff(d,0,Dateason))
DateAsOn,MS.Amount,WeekRange,MW.FromDate,MW.Todate
From AV_MemberNonPoolWise_Daily_Consol MS
WITH(NOLOCK)
--Left Join GlobalConfig_Member
GM WITH(NOLOCK) ON MS.MEMBERID=GM.Memberid
Inner Join @MemberList GM ON
MS.MEMBERID=GM.Memberid
Left Join MSO_Weekly_Slab MW WITH(NOLOCK) On
Day(MS.DateAson) BETWEEN MW.FromDate AND MW.Todate
Where MONTH(DateAsOn)=@InMonth AND
YEAR(DateAsOn)=@InYear
)A
Group By BCurrency,BillingRequired,WeekRange
)C
Group By BCurrency,BillingRequired,WeekRange
)D on B.WeekRange=D.WeekRange AND B.BCurrency=D.BCurrency AND
B.BillingRequired=D.BillingRequired
Group By B.BCurrency,B.BillingRequired,B.WeekRange
ORDER BY B.BillingRequired,B.BCurrency,B.WeekRange
Option (Optimize for (@InMonth=Null,@InYear=Null))
SET NOCOUNT OFF
GO
/****** Object: StoredProcedure [dbo].[USP_ServiceDesk_ticket_Count_Report_Pr]
Script Date: 04/03/2012 23:13:10 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[USP_ServiceDesk_ticket_Count_Report_Pr]
@MemberId BIGINT=O,
@SiteCode varchar(30)=null,
@inFlag int,
@InFromDate DATETIME,
@InToDate DATETIME,
@Inmspname VARCHAR(255) = NULL,
@type varchar(100)='all',
@InFrom int=1,
@inTo int=300
/*
-----------------------------------------------------------

EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] NULL,NULL,1,'01-01-2010','01-05-2012'

EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] NULL,null,1,'01-01-2010','01-05-


2012','Zenith Infotech DemoCenter'
EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] NULL,'Demo Center',3,'01-01-
2010','01-05-2012','Zenith Infotech DemoCenter'
EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] NULL,'amujif',3,'01-01-2010','01-05-
2012','Zenith Infotech DemoCenter'

EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] 1,null,1,'01-01-2010','01-05-


2012','Zenith Infotech DemoCenter'
EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] 1,'Demo Center',3,'01-01-2010','01-
05-2012','Zenith Infotech DemoCenter'
EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] 1,'amujif',3,'01-01-2010','01-05-
2012','Zenith Infotech DemoCenter'
EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] 1,'Demo Center 2',3,'01-01-2010','01-
05-2012','Zenith Infotech DemoCenter'

EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] 1,null,1,'01-01-2010','01-05-


2012','Zenith Infotech DemoCenter'
EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] NULL,'Demo Center',4,'01-01-
2010','01-05-2012','Zenith Infotech DemoCenter'
EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] NULL,'amujif',4,'01-01-2010','01-05-
2012','Zenith Infotech DemoCenter'
EXEC [USP_ServiceDesk_ticket_Count_Report_Pr] NULL,'Demo Center 2',4,'01-01-
2010','01-05-2012','Zenith Infotech DemoCenter'
=====================PURPOSE=====================================
To Display Desktp & Ticket Generated Count
=====================PAGE NAME(CALLING)==========================
frmServiceDesk_DesktopTicketCount_Summary.asp
=====================CREATED BY/DATE ============================
Nikasha
09-FEB-2012
-----------------------------------------------------------
*/
AS

SET NOCOUNT ON
DECLARE @MyTableVar table(RegID bigint,TaskID bigint,StatusUpdatedOn datetime
,TaskSubject varchar(max),
Resource varchar(max),AssignTo varchar(max),GroupName varchar(max),Client
varchar(max),Location varchar(max),
taskdatetime datetime ,PRIORITY int,ASSIGNTOGROUP varchar(max),ASSIGNTOUSER
int,STATUS varchar(max))

if @inFlag=1
begin
IF @Inmspname IS NULL
BEGIN

DECLARE @TMP11 TABLE(mspname VARCHAR(MAX),REGID INT ,[count]


INT,GroupName VARCHAR(MAX),client VARCHAR(MAX),
open_noc int,open_msp int,open_sd int,close_noc_msp_sd int)

INSERT INTO @TMP11


select AM.mspname,RegID,COUNT(1)[count],GroupName,client,
open_noc=count(Case when AssignTo='NOC TEAM' and status not in(102,109)
then 1 end) ,
open_msp=count(Case when AssignTo='MSP' and status not in(102,109) then 1
end) ,
open_sd=count(Case when AssignTo='ServiceDesk' and status not in(102,109)
then 1 end) ,
close_noc_msp_sd=count(Case when AssignTo in('NOC TEAM','MSP','ServiceDesk')
and status in(102,109) then 1 end)

from jmgtTaskManagement TM WITH(NOLOCK)


INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
and tm.GroupName is not null
group by AM.mspname,RegID,GroupName,client

INSERT INTO @TMP11


select AM.mspname,RegID,COUNT(1)[count],GroupName,client,
open_noc=count(Case when AssignTo='NOC TEAM' and status not in(102,109)
then 1 end) ,
open_msp=count(Case when AssignTo='MSP' and status not in(102,109) then 1
end) ,
open_sd=count(Case when AssignTo='ServiceDesk' and status not in(102,109)
then 1 end) ,
close_noc_msp_sd=count(Case when AssignTo in('NOC TEAM','MSP','ServiceDesk')
and status in(102,109) then 1 end)

from jmgttaskclosed TM WITH(NOLOCK)


INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
and tm.GroupName is not null
group by AM.mspname,RegID,GroupName,client

SELECT DISTINCT a.mspname,A.MemberID,


A.SiteCode,A.DESKTOP_COUNT, ISNULL(A.TICKET_COUNT,0) AS TICKET_COUNT,
open_noc,open_msp,open_sd,close_noc_msp_sd
FROM
(
SELECT TT.mspname,rm.MemberID, TT.client SiteCode,sum(open_noc)
open_noc,SUM(open_msp)open_msp,sum(open_sd) open_sd,
SUM(close_noc_msp_sd) close_noc_msp_sd,COUNT( RA.Regid)
DESKTOP_COUNT,sum([count]) TICKET_COUNT
FROM RegIDAttribute RA WITH(NOLOCK)
inner JOIN RegMain RM WITH(NOLOCK) ON RM.Regid = RA.Regid

LEFT join @TMP11 TT


on TT.regid=RA.regid
Where RA.Regtype = 'DPMA'
and tt.mspname is not null
group by TT.mspname, rm.MemberID ,TT.client
)A

END

IF @Inmspname IS not NULL


BEGIN
print '1'
DECLARE @TMP1 TABLE(mspname VARCHAR(MAX),REGID INT ,[count]
INT,GroupName VARCHAR(MAX),client VARCHAR(MAX),
open_noc int,open_msp int,open_sd int,close_noc_msp_sd int)

INSERT INTO @TMP1

select AM.mspname,RegID,COUNT(1)[count],GroupName,client,
open_noc=count(Case when AssignTo='NOC TEAM' and status not in(102,109)
then 1 end) ,
open_msp=count(Case when AssignTo='MSP' and status not in(102,109) then 1
end) ,
open_sd=count(Case when AssignTo='ServiceDesk' and status not in(102,109)
then 1 end) ,
close_noc_msp_sd=count(Case when AssignTo in('NOC TEAM','MSP','ServiceDesk')
and status in(102,109) then 1 end)
from jmgtTaskManagement TM WITH(NOLOCK)

INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON


TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
-- and tm.GroupName=@Inmspname
and AM.mspname=@Inmspname
and tm.GroupName is not null
group by AM.mspname,RegID,GroupName,client

INSERT INTO @TMP1

select AM.mspname,RegID,COUNT(1)[count],GroupName,client,
open_noc=count(Case when AssignTo='NOC TEAM' and status not in(102,109)
then 1 end) ,
open_msp=count(Case when AssignTo='MSP' and status not in(102,109) then 1
end) ,
open_sd=count(Case when AssignTo='ServiceDesk' and status not in(102,109)
then 1 end) ,
close_noc_msp_sd=count(Case when AssignTo in('NOC TEAM','MSP','ServiceDesk')
and status in(102,109) then 1 end)
from jmgttaskclosed TM WITH(NOLOCK)

INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON


TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
-- and tm.GroupName=@Inmspname
and AM.mspname=@Inmspname
and tm.GroupName is not null group by
AM.mspname,RegID,GroupName,client

SELECT DISTINCT a.mspname,


A.MemberID,A.SiteCode,A.DESKTOP_COUNT, ISNULL(A.TICKET_COUNT,0) AS TICKET_COUNT,
open_noc,open_msp,open_sd,close_noc_msp_sd
FROM
(
SELECT TT.mspname,rm.MemberID, TT.client SiteCode,sum(open_noc)
open_noc,SUM(open_msp)open_msp,sum(open_sd) open_sd,sum(close_noc_msp_sd)
close_noc_msp_sd,
COUNT( RA.Regid) DESKTOP_COUNT,sum([count]) TICKET_COUNT
FROM RegIDAttribute RA WITH(NOLOCK)
left JOIN RegMain RM WITH(NOLOCK) ON RM.Regid = RA.Regid

LEFT join @TMP1


TT
on TT.regid=RA.regid
Where RA.Regtype = 'DPMA'
and tt.mspname is not null
group by TT.mspname, TT.client,rm.MemberID
)A

END

end

if @inFlag=3
begin
DECLARE @TMP111 TABLE(mspname VARCHAR(MAX),REGID INT ,[count]
INT,GroupName VARCHAR(MAX),client VARCHAR(MAX),
open_noc int,open_msp int,open_sd int,close_noc_msp_sd int)

-- select * from
-- (
-- SELECT AM.mspname, RM.SiteCode,
rm.SiteId,rm.MemberID,RM.ResourceName,ROW_NUMBER() OVER(ORDER BY ra.regid DESC) AS
RNUM
-- FROM RegIDAttribute RA WITH(NOLOCK)
-- inner JOIN RegMain RM WITH(NOLOCK) ON RM.Regid = RA.Regid
-- left JOIN AdhocMnMaster AM WITH(NOLOCK) ON RM.MemberCode = AM.mspname
-- AND RM.SiteCode = AM.ClientName
-- AND RM.SiteSubCode = AM.Locationname
-- where RA.Regtype = 'DPMA'
-- and RM.SiteCode =@SiteCode
-- and rm.MemberID =@MemberId
-- AND AM.mspname = @Inmspname
--)as B
-- where RNUM between @InFrom and @inTo

INSERT INTO @TMP111


select AM.mspname,RegID,COUNT(1)[count],GroupName,client,
open_noc=count(Case when AssignTo='NOC TEAM' and status not in(102,109)
then 1 end) ,
open_msp=count(Case when AssignTo='MSP' and status not in(102,109) then 1
end) ,
open_sd=count(Case when AssignTo='ServiceDesk' and status not in(102,109)
then 1 end) ,
close_noc_msp_sd=count(Case when AssignTo in('NOC TEAM','MSP','ServiceDesk')
and status in(102,109) then 1 end)
from jmgtTaskManagement TM WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate --'01-01-2010'
and '01-05-2012'
and tm.GroupName is not null
group by AM.mspname,RegID,GroupName,client

INSERT INTO @TMP111


select AM.mspname,RegID,COUNT(1)[count],GroupName,client,
open_noc=count(Case when AssignTo='NOC TEAM' and status not in(102,109)
then 1 end) ,
open_msp=count(Case when AssignTo='MSP' and status not in(102,109) then 1
end) ,
open_sd=count(Case when AssignTo='ServiceDesk' and status not in(102,109)
then 1 end) ,
close_noc_msp_sd=count(Case when AssignTo in('NOC TEAM','MSP','ServiceDesk')
and status in(102,109) then 1 end)
from jmgttaskclosed TM WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate--'01-01-2010' and
'01-05-2012'
and tm.GroupName is not null
group by AM.mspname,RegID,GroupName,client

SELECT DISTINCT
a.mspname,A.MemberID,A.resourcename,a.SiteCode
FROM
(
SELECT TT.mspname,rm.MemberID,rm.resourcename,tt.client
SiteCode,sum(open_noc) open_noc,SUM(open_msp)open_msp,sum(open_sd) open_sd,
SUM(close_noc_msp_sd) close_noc_msp_sd,COUNT( RA.Regid)
DESKTOP_COUNT,sum([count]) TICKET_COUNT
FROM RegIDAttribute RA WITH(NOLOCK)
inner JOIN RegMain RM WITH(NOLOCK) ON RM.Regid = RA.Regid

LEFT join @TMP111 TT


on TT.regid=RA.regid
Where RA.Regtype = 'DPMA'
and tt.mspname is not null
and tt.mspname=@Inmspname --'Zenith Infotech DemoCenter'
and rm.MemberID=@MemberId
and TT.client=@SiteCode--'Demo Center 2'
group by TT.mspname,rm.MemberID,rm.resourcename,tt.client
)A

end

if @inFlag=4
begin

if @type='all'
begin

--DECLARE @MyTableVar table(RegID bigint,TaskID bigint,StatusUpdatedOn


datetime ,TaskSubject varchar(max),
--Resource varchar(max),AssignTo varchar(max),GroupName varchar(max),Client
varchar(max),Location varchar(max),
--taskdatetime datetime ,PRIORITY int,ASSIGNTOGROUP varchar(max),ASSIGNTOUSER
int,STATUS varchar(max))

insert into @MyTableVar

select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,


AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgtTaskManagement TM WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
and tm.GroupName=@Inmspname
and AssignTo in('NOC TEAM','ServiceDesk','MSP')
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
and AM.ClientName=@SiteCode
--and Status not in(102,109)

insert into @MyTableVar


select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,
AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgttaskclosed tj WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
tj.GroupName=AM.MSPNAME
AND tj.Client=AM.ClientName
AND tj.Location=AM.Locationname
and tj.GroupName=@Inmspname
and AssignTo in('NOC TEAM','ServiceDesk','MSP')
where tj.TaskDateTime BETWEEN @InFromDate AND @InToDate
--and Status not in(102,109)

select * from
(
SELECT statusName,TaskID,TaskSubject,Resource,A.AssignTo,Grp.GroupName AS
GRPNAME ,P.PriorityName
,convert(varchar,taskdatetime,113) Taskdatetime,duration,u.UserId
UserId,A.GroupName,A.Client,
A.Location,UserName,taskdatetime AS HRS,ROW_NUMBER() OVER(ORDER BY
taskdatetime DESC) AS RNUM
FROM
(
SELECT TT.TaskID,
TT.TaskSubject,TT.Resource,TT.AssignTo,TT.GroupName,TT.Client,TT.Location,

TT.PRIORITY,TT.ASSIGNTOGROUP,TT.ASSIGNTOUSER,TT.STATUS,TT.taskdatetime,
datediff(n, isnull(TT.StatusUpdatedOn, TT.taskdatetime) ,
getdate())duration
FROM RegIDAttribute RA WITH(NOLOCK)
left join @MyTableVar TT
on TT.regid=RA.regid
where RA.Regtype = 'DPMA'
) A
LEFT JOIN PRIORITYMASTER P WITH (NOLOCK) ON A.PRIORITY=P.PRIORITYID
INNER JOIN JMGTTSTATUS JMGTTSTATUS WITH (NOLOCK) ON
JMGTTSTATUS.STATUSID=A.STATUS
LEFT OUTER JOIN GROUPMASTER GRP WITH(NOLOCK) ON A.ASSIGNTOGROUP = GRP.GROUPID

LEFT OUTER JOIN USERMASTER U WITH (NOLOCK) ON A.ASSIGNTOUSER=U.USERID


)as B
where RNUM between @InFrom and @inTo
end

if @type ='open_noc'

begin

--DECLARE @MyTableVar table(RegID bigint,TaskID bigint,StatusUpdatedOn


datetime ,TaskSubject varchar(max),
--Resource varchar(max),AssignTo varchar(max),GroupName varchar(max),Client
varchar(max),Location varchar(max),
--taskdatetime datetime ,PRIORITY int,ASSIGNTOGROUP varchar(max),ASSIGNTOUSER
int,STATUS varchar(max))

insert into @MyTableVar

select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,


AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgtTaskManagement TM WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
and tm.GroupName=@Inmspname
and AssignTo in('NOC TEAM')--,'ServiceDesk','MSP')
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
and AM.ClientName=@SiteCode
and Status not in(102,109)

insert into @MyTableVar


select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,
AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgttaskclosed tj WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
tj.GroupName=AM.MSPNAME
AND tj.Client=AM.ClientName
AND tj.Location=AM.Locationname
and tj.GroupName=@Inmspname
and AssignTo in('NOC TEAM')--,'ServiceDesk','MSP')
where tj.TaskDateTime BETWEEN @InFromDate AND @InToDate
and Status not in(102,109)

select * from
(
SELECT statusName,TaskID,TaskSubject,Resource,A.AssignTo,Grp.GroupName AS
GRPNAME ,P.PriorityName
,convert(varchar,taskdatetime,113) Taskdatetime,duration,u.UserId
UserId,A.GroupName,A.Client,
A.Location,UserName,taskdatetime AS HRS,ROW_NUMBER() OVER(ORDER BY
taskdatetime DESC) AS RNUM
FROM
(
SELECT TT.TaskID,
TT.TaskSubject,TT.Resource,TT.AssignTo,TT.GroupName,TT.Client,TT.Location,

TT.PRIORITY,TT.ASSIGNTOGROUP,TT.ASSIGNTOUSER,TT.STATUS,TT.taskdatetime,
datediff(n, isnull(TT.StatusUpdatedOn, TT.taskdatetime) ,
getdate())duration
FROM RegIDAttribute RA WITH(NOLOCK)
left join @MyTableVar TT
on TT.regid=RA.regid
where RA.Regtype = 'DPMA'
) A
LEFT JOIN PRIORITYMASTER P WITH (NOLOCK) ON A.PRIORITY=P.PRIORITYID
INNER JOIN JMGTTSTATUS JMGTTSTATUS WITH (NOLOCK) ON
JMGTTSTATUS.STATUSID=A.STATUS
LEFT OUTER JOIN GROUPMASTER GRP WITH(NOLOCK) ON A.ASSIGNTOGROUP = GRP.GROUPID

LEFT OUTER JOIN USERMASTER U WITH (NOLOCK) ON A.ASSIGNTOUSER=U.USERID


)as B
where RNUM between @InFrom and @inTo
end
if @type ='open_msp'

begin

--DECLARE @MyTableVar table(RegID bigint,TaskID bigint,StatusUpdatedOn


datetime ,TaskSubject varchar(max),
--Resource varchar(max),AssignTo varchar(max),GroupName varchar(max),Client
varchar(max),Location varchar(max),
--taskdatetime datetime ,PRIORITY int,ASSIGNTOGROUP varchar(max),ASSIGNTOUSER
int,STATUS varchar(max))

insert into @MyTableVar

select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,


AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgtTaskManagement TM WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
and tm.GroupName=@Inmspname
and AssignTo in('MSP')
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
and AM.ClientName=@SiteCode
and Status not in(102,109)

insert into @MyTableVar


select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,
AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgttaskclosed tj WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
tj.GroupName=AM.MSPNAME
AND tj.Client=AM.ClientName
AND tj.Location=AM.Locationname
and tj.GroupName=@Inmspname
and AssignTo in('NOC TEAM')--,'ServiceDesk','MSP')
where tj.TaskDateTime BETWEEN @InFromDate AND @InToDate
and Status not in(102,109)

select * from
(
SELECT statusName,TaskID,TaskSubject,Resource,A.AssignTo,Grp.GroupName AS
GRPNAME ,P.PriorityName
,convert(varchar,taskdatetime,113) Taskdatetime,duration,u.UserId
UserId,A.GroupName,A.Client,
A.Location,UserName,taskdatetime AS HRS,ROW_NUMBER() OVER(ORDER BY
taskdatetime DESC) AS RNUM
FROM
(
SELECT TT.TaskID,
TT.TaskSubject,TT.Resource,TT.AssignTo,TT.GroupName,TT.Client,TT.Location,

TT.PRIORITY,TT.ASSIGNTOGROUP,TT.ASSIGNTOUSER,TT.STATUS,TT.taskdatetime,
datediff(n, isnull(TT.StatusUpdatedOn, TT.taskdatetime) ,
getdate())duration
FROM RegIDAttribute RA WITH(NOLOCK)
left join @MyTableVar TT
on TT.regid=RA.regid
where RA.Regtype = 'DPMA'
) A
LEFT JOIN PRIORITYMASTER P WITH (NOLOCK) ON A.PRIORITY=P.PRIORITYID
INNER JOIN JMGTTSTATUS JMGTTSTATUS WITH (NOLOCK) ON
JMGTTSTATUS.STATUSID=A.STATUS
LEFT OUTER JOIN GROUPMASTER GRP WITH(NOLOCK) ON A.ASSIGNTOGROUP = GRP.GROUPID

LEFT OUTER JOIN USERMASTER U WITH (NOLOCK) ON A.ASSIGNTOUSER=U.USERID


)as B
where RNUM between @InFrom and @inTo
end
if @type ='open_sd'

begin

--DECLARE @MyTableVar table(RegID bigint,TaskID bigint,StatusUpdatedOn


datetime ,TaskSubject varchar(max),
--Resource varchar(max),AssignTo varchar(max),GroupName varchar(max),Client
varchar(max),Location varchar(max),
--taskdatetime datetime ,PRIORITY int,ASSIGNTOGROUP varchar(max),ASSIGNTOUSER
int,STATUS varchar(max))

insert into @MyTableVar

select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,


AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgtTaskManagement TM WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
and tm.GroupName=@Inmspname
and AssignTo in('ServiceDesk')
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
and AM.ClientName=@SiteCode
and Status not in(102,109)

insert into @MyTableVar


select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,
AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgttaskclosed tj WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
tj.GroupName=AM.MSPNAME
AND tj.Client=AM.ClientName
AND tj.Location=AM.Locationname
and tj.GroupName=@Inmspname
and AssignTo in('ServiceDesk')--,'ServiceDesk','MSP')
where tj.TaskDateTime BETWEEN @InFromDate AND @InToDate
and Status not in(102,109)

select * from
(
SELECT statusName,TaskID,TaskSubject,Resource,A.AssignTo,Grp.GroupName AS
GRPNAME ,P.PriorityName
,convert(varchar,taskdatetime,113) Taskdatetime,duration,u.UserId
UserId,A.GroupName,A.Client,
A.Location,UserName,taskdatetime AS HRS,ROW_NUMBER() OVER(ORDER BY
taskdatetime DESC) AS RNUM
FROM
(
SELECT TT.TaskID,
TT.TaskSubject,TT.Resource,TT.AssignTo,TT.GroupName,TT.Client,TT.Location,

TT.PRIORITY,TT.ASSIGNTOGROUP,TT.ASSIGNTOUSER,TT.STATUS,TT.taskdatetime,
datediff(n, isnull(TT.StatusUpdatedOn, TT.taskdatetime) ,
getdate())duration
FROM RegIDAttribute RA WITH(NOLOCK)
left join @MyTableVar TT
on TT.regid=RA.regid
where RA.Regtype = 'DPMA'
) A
LEFT JOIN PRIORITYMASTER P WITH (NOLOCK) ON A.PRIORITY=P.PRIORITYID
INNER JOIN JMGTTSTATUS JMGTTSTATUS WITH (NOLOCK) ON
JMGTTSTATUS.STATUSID=A.STATUS
LEFT OUTER JOIN GROUPMASTER GRP WITH(NOLOCK) ON A.ASSIGNTOGROUP = GRP.GROUPID

LEFT OUTER JOIN USERMASTER U WITH (NOLOCK) ON A.ASSIGNTOUSER=U.USERID


)as B
where RNUM between @InFrom and @inTo
end
if @type ='close_noc_msp_sd'

begin

--DECLARE @MyTableVar table(RegID bigint,TaskID bigint,StatusUpdatedOn


datetime ,TaskSubject varchar(max),
--Resource varchar(max),AssignTo varchar(max),GroupName varchar(max),Client
varchar(max),Location varchar(max),
--taskdatetime datetime ,PRIORITY int,ASSIGNTOGROUP varchar(max),ASSIGNTOUSER
int,STATUS varchar(max))

insert into @MyTableVar

select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,


AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgtTaskManagement TM WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
TM.GroupName=AM.MSPNAME
AND TM.Client=AM.ClientName
AND TM.Location=AM.Locationname
and tm.GroupName=@Inmspname
and AssignTo in('NOC TEAM','ServiceDesk','MSP')
where TM.TaskDateTime BETWEEN @InFromDate AND @InToDate
and AM.ClientName=@SiteCode
and Status in(102,109)

insert into @MyTableVar


select RegID,TaskID,StatusUpdatedOn ,TaskSubject,Resource,
AssignTo,GroupName,Client,Location,
taskdatetime,PRIORITY,ASSIGNTOGROUP,ASSIGNTOUSER,STATUS
from jmgttaskclosed tj WITH(NOLOCK)
INNER JOIN AdhocTASKMnMaster AM WITH(NOLOCK) ON
tj.GroupName=AM.MSPNAME
AND tj.Client=AM.ClientName
AND tj.Location=AM.Locationname
and tj.GroupName=@Inmspname
and AssignTo in('NOC TEAM')--,'ServiceDesk','MSP')
where tj.TaskDateTime BETWEEN @InFromDate AND @InToDate
and Status in(102,109)

select * from
(
SELECT statusName,TaskID,TaskSubject,Resource,A.AssignTo,Grp.GroupName AS
GRPNAME ,P.PriorityName
,convert(varchar,taskdatetime,113) Taskdatetime,duration,u.UserId
UserId,A.GroupName,A.Client,
A.Location,UserName,taskdatetime AS HRS,ROW_NUMBER() OVER(ORDER BY
taskdatetime DESC) AS RNUM
FROM
(
SELECT TT.TaskID,
TT.TaskSubject,TT.Resource,TT.AssignTo,TT.GroupName,TT.Client,TT.Location,

TT.PRIORITY,TT.ASSIGNTOGROUP,TT.ASSIGNTOUSER,TT.STATUS,TT.taskdatetime,
datediff(n, isnull(TT.StatusUpdatedOn, TT.taskdatetime) ,
getdate())duration
FROM RegIDAttribute RA WITH(NOLOCK)
left join @MyTableVar TT
on TT.regid=RA.regid
where RA.Regtype = 'DPMA'
) A
LEFT JOIN PRIORITYMASTER P WITH (NOLOCK) ON A.PRIORITY=P.PRIORITYID
INNER JOIN JMGTTSTATUS JMGTTSTATUS WITH (NOLOCK) ON
JMGTTSTATUS.STATUSID=A.STATUS
LEFT OUTER JOIN GROUPMASTER GRP WITH(NOLOCK) ON A.ASSIGNTOGROUP = GRP.GROUPID

LEFT OUTER JOIN USERMASTER U WITH (NOLOCK) ON A.ASSIGNTOUSER=U.USERID


)as B
where RNUM between @InFrom and @inTo
end
end
SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[Usp_SrvTraceFlagStatus] Script Date:
04/03/2012 23:13:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE Proc [dbo].[Usp_SrvTraceFlagStatus]

As
/*
--------------------------------------------------------------------
====================PURPOSE=========================
-- Description: Get the details of the following
ServerName
ServiceName
ProductVersion
SQLServer Language
Product Level
Edition
TraceFlag 1222 - Deadlock TraceFlag
TraceFlag 7806 - DAC enabled
TraceFlag 1118 - TempDb Trace

=====================INPUT/OUTPUT==========================
EXEC [Usp_SrvTraceFlagStatus]

=====================PAGE NAME(CALLING)==============
=====================ALTERD BY/DATE ================

RaKeSh Tiwarekar
09-Sep-2011

*/
CREATE TABLE #TraceFlagStatus
(
ID INT IDENTITY (1,1),
Trace_Flag INT ,
TraceStatus VARCHAR(5),
GlobalTraceStatus VARCHAR(5),
SessionTraceStatus VARCHAR(5)
)

CREATE TABLE #DAC_Status


(
ID INT IDENTITY (1,1),
DAC_Flag INT ,
DACStatus VARCHAR(5),
GlobalDACStatus VARCHAR(5),
SessionDACStatus VARCHAR(5)
)
CREATE TABLE #TempDb_Status
(
ID INT IDENTITY (1,1),
TempDB_Flag INT ,
TempDBStatus VARCHAR(5),
GlobalTempDBStatus VARCHAR(5),
SessionTempDBStatus VARCHAR(5)
)

INSERT INTO #TraceFlagStatus


EXEC ('dbcc tracestatus (1222)')

INSERT INTO #DAC_Status


EXEC ( ' dbcc tracestatus (7806)')

INSERT INTO #TempDb_Status


EXEC ( ' dbcc tracestatus (1118)')

SELECT @@ServerName Server_Name,@@SERVICENAME Service_Name,


SERVERPROPERTY('productversion') Product_Version,
@@LANGUAGE Language, SERVERPROPERTY ('productlevel') Product_Level,
SERVERPROPERTY ('edition') Edition,
CASE WHEN A.TraceStatus =1 THEN 'ON' ELSE 'OFF' END AS Deadlock_Trace,
CASE WHEN B.DACStatus =1 THEN 'ON' ELSE 'OFF' END AS DAC_ENABLED,
CASE WHEN C.TempDBStatus =1 THEN 'ON' ELSE 'OFF' END AS TempDB_Trace
from #TraceFlagStatus A JOIN #DAC_Status B ON A.ID = B.ID JOIN
#TempDb_Status C ON A.ID=C.ID

DROP TABLE #TraceFlagStatus

GO
/****** Object: StoredProcedure [dbo].[Usp_SrvWiseJobInfo] Script Date:
04/03/2012 23:13:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[Usp_SrvWiseJobInfo]

As

/*
--------------------------------------------------------------------
====================PURPOSE=========================
-- Description: Get the details of the Job Schedule On Server

=====================INPUT/OUTPUT==========================
EXEC [Usp_SrvWiseJobInfo]

=====================PAGE NAME(CALLING)==============
=====================ALTERD BY/DATE ================

RaKeSh Tiwarekar
03-Sep-2011

*/

DECLARE @JOB_ID VARCHAR(200),


@SCHED_ID VARCHAR(200),
@FREQ_TYPE INT,
@FREQ_INTERVAL INT,
@FREQ_SUBDAY_TYPE INT,
@FREQ_SUBDAY_INTERVAL INT,
@FREQ_RELATIVE_INTERVAL INT,
@FREQ_RECURRENCE_FACTOR INT,
@ACTIVE_START_DATE INT,
@SCHEDULE VARCHAR(1000),
@SCHEDULE_DAY VARCHAR(200),
@START_TIME VARCHAR(10),
@END_TIME VARCHAR(10)

CREATE TABLE #SCHEDULES


(JOB_ID VARCHAR(200),
SCHED_ID VARCHAR(200),
JOB_NAME SYSNAME,
[STATUS] INT,
SCHEDULED INT NULL,
schedule VARCHAR(1000) NULL,
FREQ_TYPE INT NULL,
FREQ_INTERVAL INT NULL,
FREQ_SUBDAY_TYPE INT NULL,
FREQ_SUBDAY_INTERVAL INT NULL,
FREQ_RELATIVE_INTERVAL INT NULL,
FREQ_RECURRENCE_FACTOR INT NULL,
ACTIVE_START_DATE INT NULL,
ACTIVE_END_DATE INT NULL,
ACTIVE_START_TIME INT NULL,
ACTIVE_END_TIME INT NULL,
DATE_CREATED DATETIME NULL)

INSERT INTO #SCHEDULES (


job_id,
sched_id ,
job_name ,
[status] ,
Scheduled ,
schedule ,
freq_type,
freq_interval,
freq_subday_type,
freq_subday_interval,
freq_relative_interval,
freq_recurrence_factor,
active_start_date,
active_end_date,
active_start_time,
active_end_time,
date_created)

SELECT j.job_id,sched.schedule_id,j.name
,j.enabled,sched.enabled,NULL,sched.freq_type,sched.freq_interval,sched.freq_subday
_type,

sched.freq_subday_interval,sched.freq_relative_interval,sched.freq_recurrence_facto
r,sched.active_start_date,sched.active_end_date,
sched.active_start_time,sched.active_end_time,j.date_created FROM
msdb.dbo.sysjobs j inner join msdb.dbo.sysjobschedules s
ON j.job_id=s.job_id INNER JOIN msdb.dbo.sysschedules sched ON s.schedule_id
= sched.schedule_id
WHILE 1=1
BEGIN
SET @SCHEDULE = ''
IF (SELECT COUNT(*) FROM #SCHEDULES WHERE scheduled=1 and
schedule is null) = 0
BREAK
ELSE
BEGIN
SELECT
@job_id=job_id,@sched_id=sched_id,@freq_type=freq_type,@Freq_Interval=freq_interval
,@freq_subday_type=freq_subday_type,

@freq_subday_interval=freq_subday_interval,@freq_relative_interval=freq_relative_in
terval,@freq_recurrence_factor=freq_recurrence_factor,
@active_start_date = active_start_date,@start_time =CASE WHEN
LEFT(active_start_time, 2) IN (22, 23) AND len(active_start_time) = 6
THEN convert(varchar(2), left(active_start_time, 2) - 12) + ':' +
SUBSTRING(CAST(active_start_time AS CHAR),3, 2) + ' P.M'

WHEN left(active_start_time, 2) = (12) AND len(active_start_time) = 6


THEN cast(LEFT(active_start_time,2) as char(2)) + ':' +
SUBSTRING(CAST(active_start_time AS CHAR),3, 2) + ' P.M.'

WHEN left(active_start_time, 2) BETWEEN 13 AND 24 AND len(active_start_time) = 6


THEN convert(varchar(2), left(active_start_time, 2) - 12) + ':' +
SUBSTRING(CAST(active_start_time AS CHAR),3, 2) + ' P.M.'

WHEN left(active_start_time, 2) IN (10, 11) AND len(active_start_time) = 6


THEN cast(LEFT(active_start_time,2) as char(2)) + ':' +
SUBSTRING(CAST(active_start_time AS CHAR),3, 2) + ' A.M.'

WHEN active_start_time = 0
THEN '12:00 A.M.'

WHEN LEN(active_start_time) = 4
THEN '12:' + convert(varchar(2), left(active_start_time, 2) ) + ' A.M.'

WHEN LEN(active_start_time) = 3
THEN '12:0' + convert(varchar(2), left(active_start_time, 1) ) + '
A.M.'

WHEN LEN(active_start_time) = 2
THEN '12:00:' + convert(varchar(2), left(active_start_time, 2) ) + '
A.M.'

WHEN LEN(active_start_time) = 1
THEN '12:00:0' + convert(varchar(2), left(active_start_time, 2) ) + '
A.M.'

ELSE cast(LEFT(active_start_time,1) as char(1)) + ':' +


SUBSTRING(CAST(active_start_time AS CHAR),2, 2) + ' A.M.'
END,

@END_TIME= CASE WHEN left(active_end_time, 2) IN (22, 23) AND len(active_end_time)


= 6
THEN convert(varchar(2), left(active_end_time, 2) - 12)+ ':' +
SUBSTRING(CAST(active_end_time AS CHAR),3, 2) + ' P.M'

WHEN left(active_end_time, 2) = (12) AND len(active_end_time) = 6


THEN cast(LEFT(active_end_time,2) as char(2)) + ':' +
SUBSTRING(CAST(active_end_time AS CHAR),3, 2) + ' P.M.'

WHEN left(active_end_time, 2) BETWEEN 13 AND 24 AND len(active_end_time) = 6


THEN convert(varchar(2), left(active_end_time, 2) - 12)+ ':' +
SUBSTRING(CAST(active_end_time AS CHAR),3, 2) + ' P.M.'

WHEN left(active_end_time, 2) IN (10, 11) AND len(active_end_time) = 6


THEN cast(LEFT(active_end_time,2) as char(2)) + ':' +
SUBSTRING(CAST(active_end_time AS CHAR),3, 2) + ' A.M.'

WHEN active_end_time = 0
THEN '12:00 A.M.'

WHEN LEN(active_end_time) = 4
THEN '12:' + convert(varchar(2), left(active_end_time, 2) ) + ' A.M.'

WHEN LEN(active_end_time) = 3
THEN '12:0' + convert(varchar(2), left(active_end_time, 1) ) + ' A.M.'

WHEN LEN(active_end_time) = 2
THEN '12:00:' + convert(varchar(2), left(active_end_time, 2) ) + '
A.M.'

WHEN LEN(active_end_time) = 1
THEN '12:00:0' + convert(varchar(2), left(active_end_time, 2) ) + '
A.M.'

ELSE

cast(LEFT(active_end_time,1) as char(1)) + ':' +


SUBSTRING(CAST(active_end_time AS CHAR),2, 2) + ' A.M.'

END

FROM #SCHEDULES WHERE schedule is null AND scheduled=1

IF EXISTS(SELECT @freq_type WHERE @freq_type in (1,64))

BEGIN

SELECT @SCHEDULE = CASE @freq_type


WHEN 1 THEN 'Occurs Once, On '+cast(@active_start_date as varchar(8))+', At
'+@start_time
WHEN 64 THEN 'Occurs When SQL Server Agent Starts'

END

END

ELSE

BEGIN

IF @freq_type=4

BEGIN
SELECT @SCHEDULE = 'Occurs Every '+cast(@freq_interval as varchar(10))+' Day(s)'

END

IF @freq_type=8

BEGIN

SELECT @SCHEDULE = 'Occurs Every '+cast(@freq_recurrence_factor as


varchar(3))+' Week(s)'

SELECT @schedule_day=''

IF (SELECT (convert(int,(@freq_interval/1)) % 2)) = 1

select @schedule_day = @schedule_day+'Sun'

IF (SELECT (convert(int,(@freq_interval/2)) % 2)) = 1

select @schedule_day = @schedule_day+'Mon'

IF (SELECT (convert(int,(@freq_interval/4)) % 2)) = 1

select @schedule_day = @schedule_day+'Tue'

IF (SELECT (convert(int,(@freq_interval/8)) % 2)) = 1

select @schedule_day = @schedule_day+'Wed'

IF (SELECT (convert(int,(@freq_interval/16)) % 2)) = 1

select @schedule_day = @schedule_day+'Thu'

IF (SELECT (convert(int,(@freq_interval/32)) % 2)) = 1

select @schedule_day = @schedule_day+'Fri'

IF (SELECT (convert(int,(@freq_interval/64)) % 2)) = 1

select @schedule_day = @schedule_day+'Sat'


SELECT @SCHEDULE = @SCHEDULE+', On '+@schedule_day

END

IF @freq_type=16

BEGIN

SELECT @SCHEDULE = 'Occurs Every '+cast(@freq_recurrence_factor as


varchar(3))+' Month(s) on Day '+cast(@freq_interval as varchar(3))+' of that Month'

END

IF @freq_type=32

BEGIN

SELECT @SCHEDULE = CASE @freq_relative_interval


WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 4 THEN 'Third'
WHEN 8 THEN 'Fourth'
WHEN 16 THEN 'Last'
ELSE 'Not Applicable'
END

SELECT @SCHEDULE =CASE @freq_interval


WHEN 1 THEN 'Occurs Every '+@SCHEDULE+' Sunday of the Month'
WHEN 2 THEN 'Occurs Every '+@SCHEDULE+' Monday of the Month'
WHEN 3 THEN 'Occurs Every '+@SCHEDULE+' Tueday of the Month'
WHEN 4 THEN 'Occurs Every '+@SCHEDULE+' Wednesday of the Month'
WHEN 5 THEN 'Occurs Every '+@SCHEDULE+' Thursday of the Month'
WHEN 6 THEN 'Occurs Every '+@SCHEDULE+' Friday of the Month'
WHEN 7 THEN 'Occurs Every '+@SCHEDULE+' Saturday of the Month'
WHEN 8 THEN 'Occurs Every '+@SCHEDULE+' Day of the Month'
WHEN 9 THEN 'Occurs Every '+@SCHEDULE+' Weekday of the Month'
WHEN 10 THEN 'Occurs Every '+@SCHEDULE+' Weekend Day of the Month'
END

END

SELECT @SCHEDULE =
CASE @freq_subday_type
WHEN 1 THEN @SCHEDULE+', At '+@start_time
WHEN 2 THEN @SCHEDULE+', every '+cast(@freq_subday_interval as varchar(3))+'
Second(s) Between '+@start_time+' and '+@END_TIME
WHEN 4 THEN @SCHEDULE+', every '+cast(@freq_subday_interval as varchar(3))+'
Minute(s) Between '+@start_time+' and '+@END_TIME
WHEN 8 THEN @SCHEDULE+', every '+cast(@freq_subday_interval as varchar(3))+'
Hour(s) Between '+@start_time+' and '+@END_TIME
END

END

END

UPDATE #SCHEDULES
SET schedule=@SCHEDULE
WHERE job_id=@job_id
AND sched_id=@sched_Id

END

SELECT @@ServerName As Server_Name,Job_Name , [Status] = CASE STATUS WHEN 1


THEN 'ENABLED' WHEN 0 THEN 'DISABLED' ELSE ' ' END,
scheduled= case scheduled when 1 then 'Yes' when 0 then 'No' else ' '
end,schedule as 'Frequency' ,
convert(datetime, convert(varchar,active_start_date, 101)) AS
schedule_start_date,
convert(datetime, convert(varchar,active_end_date, 101)) AS
schedule_end_date,date_created
FROM #schedules WHERE scheduled=1 ORDER BY job_name

DROP TABLE #schedules

GO
/****** Object: StoredProcedure [dbo].[USP_SysMonitor] Script Date: 04/03/2012
23:13:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[USP_SysMonitor]


@InType int
--------------------------------------------------------------------
/*
@InType
=4 then list all database logs % used space information in current instance
=5 long running queries
=6 for batch count for each server

exec USP_SysMonitor 4

*/
--------------------------------------------------------------------
As

SET NOCOUNT ON

If (@InType = 4)

BEGIN
DBCC SQLPERF(logspace)
END

Else If (@InType = 5)

Begin
select login_time,spid,cpu,text,hostname,cmd,status,waittime
from sys.sysprocesses as qs
CROSS APPLY sys.dm_exec_sql_text( qs.sql_handle) as st
where datediff(hh,login_time ,getdate())>2
order by login_time
End
Else If (@InType = 6)
begin
SELECT * FROM sys.dm_os_performance_counters with(nolock)
WHERE OBJECT_nAME='SQLServer:SQL Statistics'
AND COUNTER_NAME='Batch Requests/sec'

end

SET NOCOUNT OFF

GO
/****** Object: StoredProcedure [dbo].[Wpost_MCTMCRelation_PRA] Script Date:
04/03/2012 23:13:12 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[Wpost_MCTMCRelation_PRA]

@InXml XML,
@OutStatus BIT OUTPUT,
@OUTXML VARCHAR(MAX) OUTPUT

AS

/*
declare @OutStatus bit,@OUTXML VARCHAR(MAX)
EXEC Wpost_MCTMCRelation_prA
'<wpmctmcagentinfo>
<mctid>5955</mctid>
<mctregid>1433879</mctregid>
<ftime>07/02/2011 19:49:12</ftime>
<mcinfo>
<mc mcname="WIN2K3-64_BIT" mcid="3718" mcguid= "12B0C41B-75C3-49BD-89EA-
04E67B89EC20" msoregid="1" fullyqname="win2k3-64_Bit" osname="Microsoft Windows
Server 2003" ostype="BIT64" />
<drdet>
<ldrive>
<inst><![CDATA[C]]></inst>
<total>20466</total>
<free>16050</free>
<used>4416</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[29874005-a743-11df-b7a5-806e6f6e6963]]></voln>
<isosdrive>1</isosdrive>
</ldrive>
<ldrive>
<inst><![CDATA[E]]></inst>
<total>400</total>
<free>371</free>
<used>29</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[92204ac6-3674-4040-9673-1fca8cb0856e]]></voln>
<isosdrive>0</isosdrive>
</ldrive>
<ldrive>
<inst><![CDATA[F]]></inst>
<total>400</total>
<free>349</free>
<used>51</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[4ce08670-7693-441d-a919-4d527f3017de]]></voln>
<isosdrive>0</isosdrive>
</ldrive>
<ldrive>
<inst><![CDATA[G]]></inst>
<total>400</total>
<free>358</free>
<used>42</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[f796944b-8a35-438c-94bb-d50afa083e4b]]></voln>
<isosdrive>0</isosdrive>
</ldrive>
<ldrive>
<inst><![CDATA[H]]></inst>
<total>846</total>
<free>769</free>
<used>77</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[1f3b3d21-2099-4946-a454-dade126d7d00]]></voln>
<isosdrive>0</isosdrive>
</ldrive>
</drdet>
</mcinfo>

<mcinfo>
<mc mcname="WIN2K3_64" mcid="5946" mcguid= "1A0EBC26-5A9E-4CA2-A93A-
A875CEC4CF2B" msoregid="" fullyqname="Win2K3_64" osname="Microsoft Windows Server
2003 R2" ostype="BIT64" />
<drdet>
<ldrive>
<inst><![CDATA[C]]></inst>
<total>15351</total>
<free>12569</free>
<used>2782</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[c03e3689-71f5-11e0-b561-806e6f6e6963]]></voln>
<isosdrive>1</isosdrive>
</ldrive>
<ldrive>
<inst><![CDATA[D]]></inst>
<total>5120</total>
<free>5092</free>
<used>28</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[515c6fb7-a913-454b-a79e-6b9a4a85fc83]]></voln>
<isosdrive>0</isosdrive>
</ldrive>
<ldrive>
<inst><![CDATA[E]]></inst>
<total>5119</total>
<free>5091</free>
<used>28</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[c16ea5ed-310e-421a-8c5f-08a3bba38c1c]]></voln>
<isosdrive>0</isosdrive>
</ldrive>
<ldrive>
<inst><![CDATA[F]]></inst>
<total>5119</total>
<free>5091</free>
<used>28</used>
<dataoffset>2097152</dataoffset>
<voln><![CDATA[ca5bba56-3c20-4188-b6d4-0c3825caa328]]></voln>
<isosdrive>0</isosdrive>
</ldrive>
</drdet>
</mcinfo>
<mcinfo>
<mc mcname="FARHAD-WIN7-64" mcid="5832" mcguid= "E27F6082-96D5-463B-BF68-
AF9732A5AD31" msoregid="1433878" fullyqname="Farhad-Win7-64" osname="Windows 7
Ultimate" ostype="BIT64" />
<drdet>
<ldrive>
<inst><![CDATA[C]]></inst>
<total>40860</total>
<free>21750</free>
<used>19110</used>
<dataoffset>4194304</dataoffset>
<voln><![CDATA[8487fbf0-bb6a-11df-8d4b-806e6f6e6963]]></voln>
<isosdrive>1</isosdrive>
</ldrive>
<ldrive>
<inst><![CDATA[D]]></inst>
<total>40960</total>
<free>32885</free>
<used>8075</used>
<dataoffset>4194304</dataoffset>
<voln><![CDATA[8487fbf1-bb6a-11df-8d4b-806e6f6e6963]]></voln>
<isosdrive>0</isosdrive>
</ldrive>
</drdet>
</mcinfo>
</wpmctmcagentinfo>' ,@OutStatus output ,@OUTXML OUTPUT
select @OutStatus,@OUTXML

=====================Webpost=========================
wpmctmcagentinfo
====================PURPOSE=========================
To insert and update md5str for Files
=====================OUTPUT==========================
Recordset
=====================CREATED BY/DATE ================
Mayank T 18/10/2010

select * from MstRegidMCMCTRel where mctid = 1234


select * from MstRegidMCRel where mcid = 1
select * from MC_RegidVolumeMonInfo where mcid = 2

=====================CHANGED BY/DATE ================


Kishan S 29th Nov2011

Update MCNAME AND FullyQName From Input XML only


Currently if its blank as discussed with Saurabh

=====================CHANGED BY/DATE ================


Kishan S 19th Jan2012
Update ISOSDRIVE as discussed with Saurabh

*/

SET NOCOUNT ON
Begin try
DECLARE @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @INXML

--DECLARE @Tab1 table(mctid bigint ,mctregid varchar(50),ftime datetime)


--DECLARE @Tab2 TABLE (mcname varchar(50) ,mcid bigint ,mcguid
varchar(300),fullyqname varchar(max),osname varchar(100) ,ostype varchar(300))
--DECLARE @Tab3 TABLE(inst varchar(300),total numeric(18,2) ,free
numeric(18,2),used numeric(18,2) ,dataoffset varchar(50),voln varchar(300)
,isosdrive char(4))

-----------------------
--INSERT INTO @TAB1
SELECT *
FROM OPENXML (@idoc, '/wpmctmcagentinfo',2)
with( mctid bigint '/wpmctmcagentinfo/@mctid'
,mctregid varchar(50) '/wpmctmcagentinfo/@mctregid'
,ftime datetime '/wpmctmcagentinfo/@ftime'
,mcname varchar(50)
'/wpmctmcagentinfo/mcinfo/mc/@mcname'
,mcid bigint
'/wpmctmcagentinfo/mcinfo/mc/@mcid'
,mcguid varchar(300)
'/wpmctmcagentinfo/mcinfo/mc/@mcguid'
,fullyqname varchar(300)
'/wpmctmcagentinfo/mcinfo/mc/@fullyqname'
,osname varchar(100)
'/wpmctmcagentinfo/mcinfo/mc/@osname'
,ostype varchar(300)
'/wpmctmcagentinfo/mcinfo/mc/@ostype'
,inst varchar(300)
'/wpmctmcagentinfo/mcinfo/drdet/ldrive/@inst'
,total numeric(18,2)
'/wpmctmcagentinfo/mcinfo/drdet/ldrive/@total'
,free numeric(18,2)
'/wpmctmcagentinfo/mcinfo/drdet/ldrive/@free'
,used numeric(18,2)
'/wpmctmcagentinfo/mcinfo/drdet/ldrive/@used'
,dataoffset varchar(50)
'/wpmctmcagentinfo/mcinfo/drdet/ldrive/@dataoffset'
,voln varchar(300)
'/wpmctmcagentinfo/mcinfo/drdet/ldrive/@voln'
,isosdrive char(4)
'/wpmctmcagentinfo/mcinfo/drdet/ldrive/@isosdrive'
)
-----------------------------------
--INSERT INTO @TAB2
--SELECT * FROM OPENXML (@idoc, '/wpmctmcagentinfo/mcinfo/mc',3)
--with(mcname varchar(50) ,mcid bigint ,mcguid varchar(300),fullyqname
varchar(300),osname varchar(100) ,ostype varchar(300))
---------------------------
--INSERT INTO @Tab3
--SELECT * FROM OPENXML (@idoc, '/wpmctmcagentinfo/mcinfo/drdet/ldrive',3)
--with(inst varchar(300) ,total numeric(18,2) ,free numeric(18,2) ,used
numeric(18,2) ,dataoffset varchar(50) ,voln varchar(300) ,isosdrive char(4))
-- DECLARE @tbl table
-- (
-- mctid bigint,mctregid bigint,mcname varchar(50),mcid
bigint,mcguid varchar(300),fullyqname varchar(1000),osname varchar(100),ostype
varchar(300),
-- inst varchar(300),total numeric(18,2),free numeric(18,2),used
numeric(18,2),dataoffset varchar(50), voln varchar(300) ,isosdrive char(4) , fdate
datetime
-- )
--
-- DECLARE @tblr table
-- (MCID bigint,MCGUID varchar(300),MCTName varchar(300),MCTID BIGINT)
--
-- INSERT INTO @tbl (mctid ,mctregid ,mcname ,mcid ,mcguid ,fullyqname
,osname ,ostype ,inst ,total, free ,used ,dataoffset ,voln, isosdrive ,fdate)
---- SELECT fileds.value('mctid[1]','bigint') ,
---- fileds.value('mctregid[1]','varchar(50)') ,
---- a.value('@mcname[1]','varchar(50)') ,
---- a.value('@mcid[1]','bigint') ,
---- a.value('@mcguid[1]','varchar(300)') ,
---- a.value('@fullyqname[1]','varchar(300)') ,
---- a.value('@osname[1]','varchar(100)') ,
---- a.value('@ostype[1]','varchar(300)') ,
---- b.value('inst[1]','varchar(300)') ,
---- b.value('total[1]','numeric(18,2)') ,
---- b.value('free[1]','numeric(18,2)') ,
---- b.value('used[1]','numeric(18,2)') ,
---- b.value('dataoffset[1]','varchar(50)') ,
---- b.value('voln[1]','varchar(300)') ,
---- b.value('isosdrive[1]','char(4)') ,
---- fileds.value('ftime[1]','datetime')
---- FROM @InXml.nodes('/wpmctmcagentinfo') as xmldata(fileds)--MstRegidMCRel
---- outer APPLY fileds.nodes('mcinfo/mc') as ta(a) --MC_RegidVolumeMonInfo
---- outer APPLY a.nodes('../drdet/ldrive') as tb(b)
--MC_RegidVolumeMonInfo
--
--select mctid ,mctregid ,mcname ,mcid ,mcguid ,fullyqname ,osname ,ostype
,inst ,total, free ,used ,dataoffset ,voln, isosdrive ,ftime
--from @tab1 cross apply @tab2 cross apply @tab3
EXEC sp_xml_removedocument @idoc
--
-- BEGIN TRANSACTION
--
---- UPDATE V SET DriveOffsiteBackup=0,MCTEnabled=0,UpDcdtime=GETDATE()
---- OUTPUT DELETED.MCID, DELETED.MCGuid, DELETED.VolumeLetter,
DELETED.VolumeLable, DELETED.vollocalguid, DELETED.SSODiskName,
DELETED.SSODiskGuid, DELETED.MCTEnabled, DELETED.FileSys, DELETED.OffsetValue,
DELETED.IQN, DELETED.TotalSize, DELETED.UsedSize,DELETED.FREE,
DELETED.PartitionType, DELETED.SystemVolume, DELETED.DriveOffsiteBackup,
DELETED.ISOSDrive, DELETED.IsMounted, DELETED.TargetIP, DELETED.DcDtime
,DELETED.UpDcdtime
---- INTO MC_RegidVolumeMonInfo_History (MCID, MCGuid, VolumeLetter,
VolumeLable, vollocalguid, SSODiskName, SSODiskGuid, MCTEnabled, FileSys,
OffsetValue, IQN, TotalSize, UsedSize,FREE, PartitionType, SystemVolume,
DriveOffsiteBackup, ISOSDrive, IsMounted, TargetIP, DcDtime,UpDcdtime)
----
---- FROM
---- @tbl T
---- inner join MC_RegidVolumeMonInfo V WITH(NOLOCK) ON
V.MCID=T.MCID
---- INNER JOIN MstRegidMCMCTRel R WITH(NOLOCk) ON R.MCID=T.MCID
AND R.MCTID<>T.MCTID
--
--
-- --------------mc relation
--
---- delete M
---- OUTPUT DELETED.MCID, DELETED.SSORegid, DELETED.Status,
DELETED.MCGUID, DELETED.SSOCloudIP, DELETED.SSOCloudUser, DELETED.ConfiguredVM,
DELETED.ConfiguredVMGuid, DELETED.DcDtime, DELETED.ConfiguredPMName,
DELETED.CoonfiguredPMGuid, DELETED.MCOSName, DELETED.MCOSVersion,
DELETED.IPAddress, DELETED.MCNAME, DELETED.MnDTime, DELETED.UpDDcDtime,
DELETED.IsMCManaged, DELETED.RecoverType, DELETED.ColoRepliType,
DELETED.FullyQName ,DELETED.OSType
---- INTO MstRegidMCRel_History( MCID, SSORegid, Status, MCGUID,
SSOCloudIP, SSOCloudUser, ConfiguredVM, ConfiguredVMGuid, DcDtime,
ConfiguredPMName, CoonfiguredPMGuid, MCOSName, MCOSVersion, IPAddress, MCNAME,
MnDTime, UpDDcDtime, IsMCManaged, RecoverType, ColoRepliType, FullyQName,OSType)
---- FROM
---- MstRegidMCRel AS M WITH(NOLOCK)
---- INNER JOIN MstRegidMCMCTRel R WITH(NOLOCK) ON R.MCID=M.MCID
---- INNER JOIN @tbl AS TT ON TT.MCTID=R.MCTID
---- left JOIN @tbl T ON T.MCID = M.MCID
----
---- WHERE T.MCID IS NULL
--
--
--
-- --MstRegidMCMCTRel
---- DELETE M
---- OUTPUT DELETED.MCID, DELETED.MCGUID,
DELETED.MCTID,DELETED.MCTRegid, DELETED.ExcludeTTMDF, DELETED.ExcludeITMDF,
DELETED.BWUsageLimit, DELETED.BWUsageMin, DELETED.DcDtime,
DELETED.UpDDcDtime,DELETED.MnDtime
---- INTO MstRegidMCMCTRel_History(MCID, MCGUID, MCTID,MCTRegid,
ExcludeTTMDF, ExcludeITMDF, BWUsageLimit, BWUsageMin, DcDtime, UpDDcDtime,MnDtime)
---- FROM MstRegidMCMCTRel AS M WITH(NOLOCK)
---- LEFT JOIN @tbl AS T ON M.MCGUID = T.MCGUID AND M.MCID = T.MCID
AND M.MCTID = T.MCTID
---- INNER JOIN @tbl AS TT ON TT.MCTID=M.MCTID
---- WHERE T.MCID IS NULL
--
--
-- UPDATE M
-- SET UpDDcDtime = GETDATE(),MCTRegid=T.mctregid
--,M.MCTID=T.MCTID
-- OUTPUT DELETED.MCID, DELETED.MCGUID, DELETED.MCTID,
DELETED.ExcludeTTMDF, DELETED.ExcludeITMDF, DELETED.BWUsageLimit,
DELETED.BWUsageMin, DELETED.DcDtime, DELETED.UpDDcDtime
-- INTO MstRegidMCMCTRel_History(MCID, MCGUID, MCTID, ExcludeTTMDF,
ExcludeITMDF, BWUsageLimit, BWUsageMin, DcDtime, UpDDcDtime)
-- FROM MstRegidMCMCTRel AS M WITH(NOLOCK)
-- INNER JOIN @tbl AS T ON M.MCGUID = T.MCGUID AND M.MCID = T.MCID
AND M.MCTID = T.MCTID
--
------------------
-- INSERT INTO @tblr(MCID,MCGUID,MCTName,MCTID)
-- SELECT distinct T.mcid,T.mcguid,ResourceName ,M.MCTID
-- FROM @tbl AS T
-- INNER JOIN MstRegidMCMCTRel AS M WITH(NOLOCK) ON M.MCGUID =
T.MCGUID AND M.MCID = T.MCID AND M.MCTID <> T.MCTID
-- left JOIN SSOREGMAIN D WITH(NOLOCK) ON D.SSOREGID=M.MCTID
--
---------------
--
--
-- INSERT INTO
MstRegidMCMCTRel(MCID,MCGUID,MCTID,MCTRegid,UpDDcDtime,MNDTIME)
-- SELECT distinct T.mcid,T.mcguid,T.mctid,T.mctregid,GETDATE() ,FDATE
-- FROM @tbl AS T
-- LEFT JOIN MstRegidMCMCTRel AS M WITH(NOLOCK) ON M.MCGUID =
T.MCGUID AND M.MCID = T.MCID --AND M.MCTID = T.MCTID
-- where M.MCID IS NULL
--
--
-- --MC_RegidVolumeMonInfo
---- UPDATE VOL
---- SET
---- VOL.IsRemoteMirror =0
---- OUTPUT DELETED.MCID, DELETED.MCGuid, DELETED.VolumeLetter,
DELETED.VolumeLable, DELETED.vollocalguid, DELETED.SSODiskName,
DELETED.SSODiskGuid, DELETED.MCTEnabled, DELETED.FileSys, DELETED.OffsetValue,
DELETED.IQN, DELETED.TotalSize, DELETED.UsedSize,DELETED.FREE,
DELETED.PartitionType, DELETED.SystemVolume, DELETED.DriveOffsiteBackup,
DELETED.ISOSDrive, DELETED.IsMounted, DELETED.TargetIP,
DELETED.DcDtime,DELETED.UpDcdtime ,deleted.IsRemoteMirror,deleted.IsLocalMirror
---- INTO MC_RegidVolumeMonInfo_History (MCID, MCGuid, VolumeLetter,
VolumeLable, vollocalguid, SSODiskName, SSODiskGuid, MCTEnabled, FileSys,
OffsetValue, IQN, TotalSize, UsedSize, FREE,PartitionType, SystemVolume,
DriveOffsiteBackup, ISOSDrive, IsMounted,
---- TargetIP,
DcDtime,UpDcdtime,IsRemoteMirror,IsLocalMirror)
---- FROM MC_RegidVolumeMonInfo AS VOL
---- INNER JOIN @tbl T ON VOL.MCID= T.mcid
---- LEFT JOIN @tbl E ON VOL.MCID= E.mcid and VOL.VolumeLetter = E.inst
---- WHERE E.inst IS NULL
----
----
---- UPDATE VOL
---- SET
---- VOL.RemoteMirror
=null,RemoteFlush=null,PrevRemoteFlush=null,LastRemoteFlushChange=null,RemoteBaseSt
atus=null
----
---- FROM MC_QALookup AS VOL
---- INNER JOIN @tbl T ON VOL.MCID= T.mcid
---- LEFT JOIN @tbl E ON VOL.MCID= E.mcid and VOL.VolumeName = E.inst
---- WHERE E.inst IS NULL
----
-- UPDATE VOL
-- SET
-- VOL.ISOSDrive=Case when ISNULL(T.ISOSDrive,'')='' then
VOL.ISOSDrive ELSE T.ISOSDrive END,
-- VOL.UpDcdtime = getdate()
-- OUTPUT DELETED.MCID, DELETED.MCGuid, DELETED.VolumeLetter,
DELETED.VolumeLable, DELETED.vollocalguid, DELETED.SSODiskName,
DELETED.SSODiskGuid, DELETED.MCTEnabled, DELETED.FileSys, DELETED.OffsetValue,
DELETED.IQN, DELETED.TotalSize, DELETED.UsedSize,DELETED.FREE,
DELETED.PartitionType, DELETED.SystemVolume, DELETED.DriveOffsiteBackup,
DELETED.ISOSDrive, DELETED.IsMounted, DELETED.TargetIP, DELETED.DcDtime
,DELETED.UpDcdtime,deleted.IsRemoteMirror,deleted.IsLocalMirror
-- INTO MC_RegidVolumeMonInfo_History (MCID, MCGuid, VolumeLetter,
VolumeLable, vollocalguid, SSODiskName, SSODiskGuid, MCTEnabled, FileSys,
OffsetValue, IQN, TotalSize, UsedSize,FREE, PartitionType, SystemVolume,
DriveOffsiteBackup, ISOSDrive, IsMounted, TargetIP,
DcDtime,UpDcdtime,IsRemoteMirror,IsLocalMirror)
--
-- FROM MC_RegidVolumeMonInfo VOL WITH(NOLOCK)
-- INNER JOIN @tbl T ON VOL.MCID= T.mcid and VOL.VolumeLetter =
T.inst AND VOL.MCGuid=T.MCGuid
----
---- INSERT INTO MC_RegidVolumeMonInfo(IsRemoteMirror,MCID,
MCGuid,VolumeLetter,VolumeLable,TotalSize,UsedSize,OffsetValue,Free,UpDcdtime,vollo
calguid )
---- SELECT DISTINCT 1,T.mcid,T.mcguid,T.inst,T.voln,T.total,T.used,
T.dataoffset,T.free,getdate(),voln
---- FROM @tbl T
---- LEFT JOIN MC_RegidVolumeMonInfo VOL WITH(NOLOCK) ON VOL.MCID=
T.MCID
---- and VOL.VolumeLetter = T.inst AND
VOL.MCGuid=T.MCGuid
---- WHERE VOL.MCID IS NULL
--
-- --MstRegidMCRel
--
--
--
--
-- UPDATE M SET
-- M.MCNAME =Case when ISNULL(M.MCNAME,'')='' then T.mcname ELSE
M.MCNAME END,UpDDcDtime = GETDATE(),MCGUID=t.mcguid,M.FullyQName =Case when
isnull(M.FullyQName,'')='' then T.fullyqname else M.FullyQName end,
-- M.MCOSName = T.osname ,M.OSType = T.ostype
-- OUTPUT DELETED.MCID, DELETED.SSORegid, DELETED.Status,
DELETED.MCGUID, DELETED.SSOCloudIP, DELETED.SSOCloudUser, DELETED.ConfiguredVM,
DELETED.ConfiguredVMGuid, DELETED.DcDtime, DELETED.ConfiguredPMName,
DELETED.CoonfiguredPMGuid, DELETED.MCOSName, DELETED.MCOSVersion,
DELETED.IPAddress, DELETED.MCNAME, DELETED.MnDTime, DELETED.UpDDcDtime,
DELETED.IsMCManaged, DELETED.RecoverType, DELETED.ColoRepliType,
DELETED.FullyQName ,DELETED.OSType
-- INTO MstRegidMCRel_History( MCID, SSORegid, Status, MCGUID,
SSOCloudIP, SSOCloudUser, ConfiguredVM, ConfiguredVMGuid, DcDtime,
ConfiguredPMName, CoonfiguredPMGuid, MCOSName, MCOSVersion, IPAddress, MCNAME,
MnDTime, UpDDcDtime, IsMCManaged, RecoverType, ColoRepliType, FullyQName,OSType)
-- FROM
-- MstRegidMCRel AS M WITH(NOLOCK)
-- INNER JOIN @tbl T ON T.MCID = M.MCID
--
-- INSERT INTO
MstRegidMCRel(MCID,MCNAME,UpDDcDtime,MCGUID,fullyqname,MCOSName,OSType)
-- SELECT distinct T.MCID
,T.mcname,GETDATE(),T.MCGUID,t.fullyqname,T.osname ,T.ostype
-- FROM
-- @tbl T
-- LEFT JOIN MstRegidMCRel AS M WITH(NOLOCK) ON T.MCID = M.MCID
-- WHERE M.MCID IS NULL
----
---- INSERT INTO MC_QALookup (MCID,MCGUID,VolGUID,updcdtime,VolumeName)
---- SELECT distinct T.MCID,T.MCGUID,t.voln,getdate(),T.inst
---- FROM @tbl T
---- LEFT JOIN MC_QALookup as L WITH(NOLOCK) ON l.MCID= T.MCID
---- and l.VolumeName = T.inst AND
l.MCGuid=T.MCGuid
---- WHERE L.VolumeName IS NULL
--
--
-- --MC_RegidDISkInfo
---- INSERT INTO MC_RegidDISkInfo( MCdtime,MCID, MCGuid, VolumeLetter,
TotalSize, UsedSize,ISOSDrive)
---- SELECT DISTINCT fdate,
T.MCID,T.MCGUID,T.inst,T.total,T.used,T.isosdrive
---- FROM @tbl T
---- LEFT JOIN MC_RegidDISkInfo VOL WITH(NOLOCK) ON VOL.MCID= T.MCID
AND VOL.MCGuid = T.MCGUID and VOL.VolumeLetter = T.inst
---- WHERE VOL.MCID is null
----
---- update VOL set
---- MCdtime = T.fdate,
---- TotalSize = T.total ,
---- UsedSize = T.used,
---- ISOSDrive = T.isosdrive
---- FROM @tbl T
---- INNER JOIN MC_RegidDISkInfo VOL WITH(NOLOCK) ON VOL.MCID=
T.MCID AND VOL.MCGuid = T.MCGUID and VOL.VolumeLetter = T.inst
----
-- if exists(select top 1 mctid from @tblr)
-- begin
-- set @outxml='<mcrelation>'
-- SET @OUTXML=@OUTXML+(SELECT MCID as mcid,MCGUID as
mcguid,MCTNAME AS mctname,mctid
-- FROM @tblr AS mcrelation FOR XML AUTO)
-- set @outxml=@outxml + '</mcrelation>'
-- end
-- ELSE
-- BEGIN
-- set @outxml='<mcrelation>
-- </mcrelation>'
-- END

-- COMMIT TRANSACTION
-- set @OutStatus = 1

end try

begin catch
select error_message()
ROLLBACK TRANSACTION
set @OutStatus = 0
end catch

SET NOCOUNT OFF

You might also like