From 31158f165703abc4355b01e0c0c110dcfafe85fb Mon Sep 17 00:00:00 2001 From: Blake Drumm Date: Fri, 4 Nov 2022 12:45:05 -0400 Subject: [PATCH] Push new SQL Queries :books: --- .../Data Warehouse/DW_AggregationHistory.sql | 2 +- .../Data Warehouse/DW_Alerts_ByCount.sql | 6 ++ .../Data Warehouse/DW_Alerts_ByDay.sql | 5 ++ .../Data Warehouse/DW_Alerts_ByOldest.sql | 15 ++++ .../Data Warehouse/DW_Alerts_ByRepeat.sql | 6 ++ .../DW_Greyed_Out_Reason_Codes.sql | 2 +- .../Data Warehouse/DW_Perf_byCounter.sql | 18 ++--- .../DW_Perf_byManagedEntity.sql | 18 ++--- SQL Queries/Data Warehouse/Index_Maint_DW.sql | 9 --- .../Data Warehouse/MG_SQLPatchVersion_DW.sql | 2 +- SQL Queries/Data Warehouse/SQL_DBOwner_DW.sql | 8 +-- SQL Queries/Data Warehouse/SQL_DBSize_DW.sql | 2 +- .../Data Warehouse/SQL_DBSize_DW_TempDB.sql | 30 ++++++++ .../SQL_ErrorLogLocation_DW.sql | 2 +- .../SQL_Primary_Replicas_DW.sql | 36 +++++----- .../Data Warehouse/SQL_Properties_DW.sql | 4 +- .../Data Warehouse/SQL_UserMapping_DW.sql | 64 ++++++++--------- .../OperationsManager/Alerts_ByCount.sql | 2 +- .../OperationsManager/Alerts_ByDay.sql | 4 +- .../OperationsManager/Alerts_ByOldest.sql | 24 +++---- .../OperationsManager/Alerts_ByRepeat.sql | 4 +- .../Broken_Relationships.sql | 28 ++++---- .../OperationsManager/ConfigChurn_OpsDB.sql | 2 +- .../OperationsManager/Configuration_OpsDB.sql | 20 +++--- .../CriticalState_Monitors.sql | 28 ++++---- SQL Queries/OperationsManager/Discoveries.sql | 26 +++---- .../Event29181_CastNotValid.sql | 50 ++++++------- .../Event29181_System.DBNull-Continued.sql | 70 +++++++++--------- .../Event29181_System.DBNull.sql | 24 +++---- .../OperationsManager/Events_ByComputer.sql | 2 +- .../OperationsManager/Events_ByNumber.sql | 8 ++- .../OperationsManager/Grooming_Logs_OpsDB.sql | 2 +- .../HealthService_Heartbeat.sql | 14 ++-- .../HealthService_Inventory.sql | 2 +- .../HealthService_LastContact.sql | 62 ++++++++-------- .../HealthService_Pending.sql | 30 ++++---- .../HeathService_Avail_Last_7days.sql | 40 +++++------ .../Index_Maintenance_OpsDB.sql | 30 ++++---- .../Instances_Hosted_AMSRP.sql | 6 +- SQL Queries/OperationsManager/MG_Overview.sql | 2 +- .../MG_SQLPatchVersion_OpsDB.sql | 2 +- .../MP_EventDescription_BadPractice.sql | 8 +-- SQL Queries/OperationsManager/MP_Removals.sql | 2 +- .../OperationsManager/Maintenance_Mode.sql | 64 ++++++++--------- .../Maintenance_Mode_ManagementServers.sql | 64 ++++++++--------- .../OperationsManager/ManagementPacks.sql | 28 ++++---- .../OperationsManager/ManagementServers.sql | 21 ++---- .../ManagementServers_Availability.sql | 27 +++++++ .../Notifications_Channels.sql | 6 +- .../Notifications_Subscriptions.sql | 72 +++++++++---------- SQL Queries/OperationsManager/Orphaned.sql | 68 +++++++++--------- .../PartitionAndGroom_Retention.sql | 20 +++--- ...{Perf_byCounter.sql => Perf_ByCounter.sql} | 7 +- .../Recently_Changed_Disc_OpsDB.sql | 26 +++---- .../OperationsManager/Relationships.sql | 6 +- .../OperationsManager/ResourcePools.sql | 4 +- .../OperationsManager/Resource_Pool_OpsDB.sql | 34 --------- .../OperationsManager/RunAsAccounts_OpsDB.sql | 26 +++---- .../OperationsManager/RunAsProfiles.sql | 40 +++++------ .../OperationsManager/SQL_DBOwner_OpsDB.sql | 8 +-- .../OperationsManager/SQL_DBSize_OpsDB.sql | 2 +- .../SQL_DBSize_OpsDB_TempDB.sql | 30 ++++++++ .../SQL_ErrorLogLocation_OpsDB.sql | 2 +- .../SQL_Primary_Replicas_OpsMgr.sql | 36 +++++----- .../SQL_Properties_OpsDB.sql | 4 +- .../SQL_UserMapping_OpsDB.sql | 64 ++++++++--------- .../State_UnhealthyMonitors.sql | 26 +++---- SQL Queries/OperationsManager/TaskStatus.sql | 48 ++++++------- SQL Queries/OperationsManager/UNIX_Agents.sql | 2 +- SQL Queries/OperationsManager/UserRoles.sql | 8 +-- 70 files changed, 765 insertions(+), 699 deletions(-) create mode 100644 SQL Queries/Data Warehouse/DW_Alerts_ByCount.sql create mode 100644 SQL Queries/Data Warehouse/DW_Alerts_ByDay.sql create mode 100644 SQL Queries/Data Warehouse/DW_Alerts_ByOldest.sql create mode 100644 SQL Queries/Data Warehouse/DW_Alerts_ByRepeat.sql delete mode 100644 SQL Queries/Data Warehouse/Index_Maint_DW.sql create mode 100644 SQL Queries/Data Warehouse/SQL_DBSize_DW_TempDB.sql create mode 100644 SQL Queries/OperationsManager/ManagementServers_Availability.sql rename SQL Queries/OperationsManager/{Perf_byCounter.sql => Perf_ByCounter.sql} (56%) delete mode 100644 SQL Queries/OperationsManager/Resource_Pool_OpsDB.sql create mode 100644 SQL Queries/OperationsManager/SQL_DBSize_OpsDB_TempDB.sql diff --git a/SQL Queries/Data Warehouse/DW_AggregationHistory.sql b/SQL Queries/Data Warehouse/DW_AggregationHistory.sql index a80471b..d8f44b5 100644 --- a/SQL Queries/Data Warehouse/DW_AggregationHistory.sql +++ b/SQL Queries/Data Warehouse/DW_AggregationHistory.sql @@ -11,4 +11,4 @@ SELECT ds.DatasetDefaultName, FROM StandardDatasetAggregationHistory sdah WITH(NOLOCK) JOIN Dataset ds WITH (NOLOCK) ON sdah.DatasetId = ds.DatasetId JOIN AggregationType atype WITH (NOLOCK) ON sdah.AggregationTypeId = atype.AggregationTypeId -ORDER BY StandardDatasetAggregationHistoryRowId DESC +ORDER BY sdah.FirstAggregationDurationSeconds DESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/DW_Alerts_ByCount.sql b/SQL Queries/Data Warehouse/DW_Alerts_ByCount.sql new file mode 100644 index 0000000..4760e64 --- /dev/null +++ b/SQL Queries/Data Warehouse/DW_Alerts_ByCount.sql @@ -0,0 +1,6 @@ +SELECT TOP 50 SUM(1) AS AlertCount, AlertName, AlertDescription, AlertProblemGuid, MonitorSystemName +FROM Alert.vAlert va INNER JOIN +Monitor mon on mon.MonitorGuid = va.AlertProblemGuid +WHERE RaisedDateTime is not NULL +GROUP BY AlertName, AlertDescription, AlertProblemGuid, MonitorSystemName +ORDER BY AlertCount DESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/DW_Alerts_ByDay.sql b/SQL Queries/Data Warehouse/DW_Alerts_ByDay.sql new file mode 100644 index 0000000..3ff3a6f --- /dev/null +++ b/SQL Queries/Data Warehouse/DW_Alerts_ByDay.sql @@ -0,0 +1,5 @@ +SELECT CONVERT(VARCHAR(20), DBCreatedDateTime, 102) AS DayAdded, COUNT(*) AS NumAlertsPerDay +FROM Alert.vAlert +WHERE RaisedDateTime is not NULL +GROUP BY CONVERT(VARCHAR(20), DBCreatedDateTime, 102) +ORDER BY DayAdded DESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/DW_Alerts_ByOldest.sql b/SQL Queries/Data Warehouse/DW_Alerts_ByOldest.sql new file mode 100644 index 0000000..f65d561 --- /dev/null +++ b/SQL Queries/Data Warehouse/DW_Alerts_ByOldest.sql @@ -0,0 +1,15 @@ +SELECT TOP 50 DATEDIFF(Day,RaisedDateTime,current_timestamp) AS DaysOpened, Case Severity +When 0 then 'Information' +When 1 then 'Warning' +When 2 then 'Critical' +End as [Severity],RepeatCount, AlertName, AlertDescription, MonitorSystemName, MonitorGuid, ParameterValue, Case ResolutionState +When 0 then 'Open' +End as [ResolutionState] +FROM Alert.vAlert va INNER JOIN +Monitor mon on mon.MonitorGuid = va.AlertProblemGuid INNER JOIN +Alert.vAlertParameter vap on va.AlertGuid = vap.AlertGuid INNER JOIN +Alert.vAlertResolutionState vars on va.AlertGuid = vars.AlertGuid +WHERE RaisedDateTime is not NULL +AND ResolutionState = 0 +GROUP BY AlertName, RepeatCount, RaisedDateTime, Severity, MonitorSystemName, DWLastModifiedDateTime, AlertDescription, ParameterValue, MonitorGuid, ResolutionState +ORDER BY DaysOpened DESC, RepeatCount DESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/DW_Alerts_ByRepeat.sql b/SQL Queries/Data Warehouse/DW_Alerts_ByRepeat.sql new file mode 100644 index 0000000..c1c089e --- /dev/null +++ b/SQL Queries/Data Warehouse/DW_Alerts_ByRepeat.sql @@ -0,0 +1,6 @@ +SELECT TOP 50 RepeatCount, AlertName, AlertDescription, AlertProblemGuid, MonitorSystemName +FROM Alert.vAlert va INNER JOIN +Monitor mon on mon.MonitorGuid = va.AlertProblemGuid +WHERE RaisedDateTime is not NULL +GROUP BY AlertName, RepeatCount, AlertDescription, AlertProblemGuid, MonitorSystemName +ORDER BY RepeatCount DESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/DW_Greyed_Out_Reason_Codes.sql b/SQL Queries/Data Warehouse/DW_Greyed_Out_Reason_Codes.sql index b148001..396f97b 100644 --- a/SQL Queries/Data Warehouse/DW_Greyed_Out_Reason_Codes.sql +++ b/SQL Queries/Data Warehouse/DW_Greyed_Out_Reason_Codes.sql @@ -3,4 +3,4 @@ AS OutageDays, HSO.ReasonCode, DS.Name AS ReasonString FROM vManagedEntity AS ME INNER JOIN vHealthServiceOutage AS HSO ON HSO.ManagedEntityRowId = ME.ManagedEntityRowId INNER JOIN vStringResource AS SR ON HSO.ReasonCode = REPLACE(LEFT(SR.StringResourceSystemName, LEN(SR.StringResourceSystemName) - CHARINDEX('.', REVERSE(SR.StringResourceSystemName))), 'System.Availability.StateData.Reasons.', '') INNER JOIN vDisplayString AS DS ON DS.ElementGuid = SR.StringResourceGuid WHERE (HSO.EndDateTime IS NULL) AND (SR.StringResourceSystemName LIKE 'System.Availability.StateData.Reasons.[0-9]%') AND DS.LanguageCode = 'ENU' -ORDER BY OutageStartDateTime \ No newline at end of file +ORDER BY OutageStartDateTime DESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/DW_Perf_byCounter.sql b/SQL Queries/Data Warehouse/DW_Perf_byCounter.sql index 93233d9..b0b8472 100644 --- a/SQL Queries/Data Warehouse/DW_Perf_byCounter.sql +++ b/SQL Queries/Data Warehouse/DW_Perf_byCounter.sql @@ -1,10 +1,10 @@ -/*Top 30 performance insertions: */ -select TOP 30 PR.CounterName,PR.ObjectName, vR.ruledefaultname As RuleName, COUNT(PR.countername) AS Total -from Perf.vPerfRaw perf -join ManagedEntity ME WITH(NOLOCK) on perf.ManagedEntityRowId = ME.ManagedEntityRowId -join PerformanceRuleInstance PRI WITH(NOLOCK) on perf.PerformanceRuleInstanceRowId = PRI.PerformanceRuleInstanceRowId -join PerformanceRule PR WITH(NOLOCK) on PRI.RuleRowId = PR.RuleRowId -join vRule vR on vR.rulerowid = PR.RuleRowId -where perf.DateTime > GetUTCDate() -48 -GROUP BY PR.ObjectName, PR.CounterName, vr.ruledefaultname +/*Top 30 performance insertions: */ +select TOP 30 PR.CounterName,PR.ObjectName, vR.ruledefaultname As RuleName, COUNT(PR.countername) AS Total +from Perf.vPerfRaw perf +join ManagedEntity ME WITH(NOLOCK) on perf.ManagedEntityRowId = ME.ManagedEntityRowId +join PerformanceRuleInstance PRI WITH(NOLOCK) on perf.PerformanceRuleInstanceRowId = PRI.PerformanceRuleInstanceRowId +join PerformanceRule PR WITH(NOLOCK) on PRI.RuleRowId = PR.RuleRowId +join vRule vR on vR.rulerowid = PR.RuleRowId +where perf.DateTime > GetUTCDate() -48 +GROUP BY PR.ObjectName, PR.CounterName, vr.ruledefaultname ORDER BY COUNT (PR.CounterName) dESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/DW_Perf_byManagedEntity.sql b/SQL Queries/Data Warehouse/DW_Perf_byManagedEntity.sql index 7310629..35a232e 100644 --- a/SQL Queries/Data Warehouse/DW_Perf_byManagedEntity.sql +++ b/SQL Queries/Data Warehouse/DW_Perf_byManagedEntity.sql @@ -1,10 +1,10 @@ -select r.RuleDefaultName, pr.ObjectName, pr.CounterName, mp.ManagementPackDefaultName as MPName, COUNT(me.ManagedEntityDefaultName) AS Total -from Perf.vPerfRaw perf -join vPerformanceRuleInstance PRI on perf.PerformanceRuleInstanceRowId = PRI.PerformanceRuleInstanceRowId -join vPerformanceRule pr on PRI.RuleRowId = PR.RuleRowId -join vManagedEntity me on perf.ManagedEntityRowId = ME.ManagedEntityRowId -join [dbo].[vRule] r on r.RuleRowId = PR.RuleRowId -join vManagementPack mp on r.ManagementPackRowId = mp.ManagementPackRowId -where perf.DateTime > GetUTCDate() -48 -GROUP BY PR.ObjectName, PR.CounterName, r.ruledefaultname, mp.ManagementPackDefaultName +select r.RuleDefaultName, pr.ObjectName, pr.CounterName, mp.ManagementPackDefaultName as MPName, COUNT(me.ManagedEntityDefaultName) AS Total +from Perf.vPerfRaw perf +join vPerformanceRuleInstance PRI on perf.PerformanceRuleInstanceRowId = PRI.PerformanceRuleInstanceRowId +join vPerformanceRule pr on PRI.RuleRowId = PR.RuleRowId +join vManagedEntity me on perf.ManagedEntityRowId = ME.ManagedEntityRowId +join [dbo].[vRule] r on r.RuleRowId = PR.RuleRowId +join vManagementPack mp on r.ManagementPackRowId = mp.ManagementPackRowId +where perf.DateTime > GetUTCDate() -48 +GROUP BY PR.ObjectName, PR.CounterName, r.ruledefaultname, mp.ManagementPackDefaultName ORDER BY COUNT (me.ManagedEntityDefaultName) DESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/Index_Maint_DW.sql b/SQL Queries/Data Warehouse/Index_Maint_DW.sql deleted file mode 100644 index 2eefa5e..0000000 --- a/SQL Queries/Data Warehouse/Index_Maint_DW.sql +++ /dev/null @@ -1,9 +0,0 @@ -select basetablename, optimizationstartdatetime, optimizationdurationseconds, - beforeavgfragmentationinpercent, afteravgfragmentationinpercent, - optimizationmethod, onlinerebuildlastperformeddatetime -from StandardDatasetOptimizationHistory sdoh -inner join StandardDatasetAggregationStorageIndex sdasi -on sdoh.StandardDatasetAggregationStorageIndexRowId = sdasi.StandardDatasetAggregationStorageIndexRowId -inner join StandardDatasetAggregationStorage sdas -on sdasi.StandardDatasetAggregationStorageRowId = sdas.StandardDatasetAggregationStorageRowId -ORDER BY optimizationdurationseconds DESC \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/MG_SQLPatchVersion_DW.sql b/SQL Queries/Data Warehouse/MG_SQLPatchVersion_DW.sql index 1d7192c..6cf9501 100644 --- a/SQL Queries/Data Warehouse/MG_SQLPatchVersion_DW.sql +++ b/SQL Queries/Data Warehouse/MG_SQLPatchVersion_DW.sql @@ -1,2 +1,2 @@ --- Get the Data Warehouse Update Rollup Version. +-- Get the Data Warehouse Update Rollup Version. select * from [dbo].[SqlPatchVersion] WITH (NOLOCK) \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/SQL_DBOwner_DW.sql b/SQL Queries/Data Warehouse/SQL_DBOwner_DW.sql index 60a78a2..194c571 100644 --- a/SQL Queries/Data Warehouse/SQL_DBOwner_DW.sql +++ b/SQL Queries/Data Warehouse/SQL_DBOwner_DW.sql @@ -1,4 +1,4 @@ -select DB_NAME(DB_ID()), suser_sname(owner_sid) AS 'Owner' -from sys.databases sdb -WHERE database_id = DB_ID() -go +-- Get current context DB Owner +select DB_NAME(DB_ID()), suser_sname(owner_sid) AS 'Owner' +from sys.databases sdb +WHERE database_id = DB_ID() \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/SQL_DBSize_DW.sql b/SQL Queries/Data Warehouse/SQL_DBSize_DW.sql index 0a4a493..b582ff6 100644 --- a/SQL Queries/Data Warehouse/SQL_DBSize_DW.sql +++ b/SQL Queries/Data Warehouse/SQL_DBSize_DW.sql @@ -25,4 +25,4 @@ sf.FILENAME AS 'Location', sf.FILEID AS 'FileId' FROM dbo.sysfiles sf WITH (NOLOCK) JOIN sys.master_files smf WITH (NOLOCK) ON smf.physical_name = sf.filename -ORDER BY FileId +ORDER BY FileId \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/SQL_DBSize_DW_TempDB.sql b/SQL Queries/Data Warehouse/SQL_DBSize_DW_TempDB.sql new file mode 100644 index 0000000..4d93249 --- /dev/null +++ b/SQL Queries/Data Warehouse/SQL_DBSize_DW_TempDB.sql @@ -0,0 +1,30 @@ +-- Modified 2/9/2022 - Included Free Space %, added MB to value fields. +-- Modified 6/21/2022 - Attempted to fix Arithmetic Overflow error when run in large environments. Added 'SpaceUsed(%)' and 'AutoGrowthStatus' columns. +-- Blake Drumm (blakedrumm@microsoft.com) +USE tempdb + +SELECT sf.NAME AS 'Name', +CONCAT(convert(decimal(12,2), round(sf.size/128.000, 2)), ' MB') AS 'FileSize(MB)', +CONCAT(convert(int, round(100 * convert(bigint,(sf.size-fileproperty(sf.name, 'SpaceUsed'))) / convert(bigint,sf.size), 2)),' %') AS 'FreeSpace(%)', +CONCAT(convert(decimal(12,2), round((sf.size-fileproperty(sf.name, 'SpaceUsed'))/128.000, 2)), ' MB') AS 'FreeSpace(MB)', +CONCAT(convert(int, 100 - (round(100 * convert(bigint,(sf.size-fileproperty(sf.name, 'SpaceUsed'))) / convert(bigint,sf.size), 2))),' %') AS 'SpaceUsed(%)', +CONCAT(convert(decimal(12,2), round(fileproperty(sf.name, 'SpaceUsed')/128.000, 2)), ' MB') AS 'SpaceUsed(MB)', +CASE smf.growth + WHEN 0 THEN 'Disabled' + ELSE 'Enabled' +END AS 'AutoGrowthStatus', +CASE smf.is_percent_growth + WHEN 1 THEN CONCAT(CONVERT(bigint, smf.growth), ' %') + ELSE CONCAT(convert(decimal(12,2), smf.growth/128),' MB') +END AS 'AutoGrowth', +CASE (sf.maxsize) + WHEN -1 THEN 'Unlimited' + WHEN 268435456 THEN 'Max Size (2TB)' + ELSE CONCAT(convert(decimal(12,2), round(sf.maxsize/128.000, 2)), ' MB') +END AS 'AutoGrowthMB(MAX)', +sf.status, +sf.FILENAME AS 'Location', +sf.FILEID AS 'FileId' +FROM dbo.sysfiles sf WITH (NOLOCK) +JOIN sys.master_files smf WITH (NOLOCK) ON smf.physical_name = sf.filename +ORDER BY FileId \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/SQL_ErrorLogLocation_DW.sql b/SQL Queries/Data Warehouse/SQL_ErrorLogLocation_DW.sql index eb1b5c3..5af4a0e 100644 --- a/SQL Queries/Data Warehouse/SQL_ErrorLogLocation_DW.sql +++ b/SQL Queries/Data Warehouse/SQL_ErrorLogLocation_DW.sql @@ -1 +1 @@ -xp_readerrorlog 0, 1, N'Logging SQL Server messages in file' +xp_readerrorlog 0, 1, N'Logging SQL Server messages in file' diff --git a/SQL Queries/Data Warehouse/SQL_Primary_Replicas_DW.sql b/SQL Queries/Data Warehouse/SQL_Primary_Replicas_DW.sql index 5099976..115dbf1 100644 --- a/SQL Queries/Data Warehouse/SQL_Primary_Replicas_DW.sql +++ b/SQL Queries/Data Warehouse/SQL_Primary_Replicas_DW.sql @@ -1,19 +1,19 @@ -IF SERVERPROPERTY ('IsHadrEnabled') = 1 -BEGIN -SELECT - AGC.name -- Availability Group - , RCS.replica_server_name -- SQL cluster node name - , ARS.role_desc -- Replica Role - , AGL.dns_name -- Listener Name -FROM - sys.availability_groups_cluster AS AGC - INNER JOIN sys.dm_hadr_availability_replica_cluster_states AS RCS - ON - RCS.group_id = AGC.group_id - INNER JOIN sys.dm_hadr_availability_replica_states AS ARS - ON - ARS.replica_id = RCS.replica_id - INNER JOIN sys.availability_group_listeners AS AGL - ON - AGL.group_id = ARS.group_id +IF SERVERPROPERTY ('IsHadrEnabled') = 1 +BEGIN +SELECT + AGC.name -- Availability Group + , RCS.replica_server_name -- SQL cluster node name + , ARS.role_desc -- Replica Role + , AGL.dns_name -- Listener Name +FROM + sys.availability_groups_cluster AS AGC + INNER JOIN sys.dm_hadr_availability_replica_cluster_states AS RCS + ON + RCS.group_id = AGC.group_id + INNER JOIN sys.dm_hadr_availability_replica_states AS ARS + ON + ARS.replica_id = RCS.replica_id + INNER JOIN sys.availability_group_listeners AS AGL + ON + AGL.group_id = ARS.group_id END \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/SQL_Properties_DW.sql b/SQL Queries/Data Warehouse/SQL_Properties_DW.sql index 9349460..d11467a 100644 --- a/SQL Queries/Data Warehouse/SQL_Properties_DW.sql +++ b/SQL Queries/Data Warehouse/SQL_Properties_DW.sql @@ -1,4 +1,4 @@ -SELECT CASE +SELECT CASE (SELECT is_broker_enabled FROM sys.databases WHERE name=db_name()) @@ -49,4 +49,4 @@ SELECT CASE END AS [IsFullTextInstalled], CONVERT(nvarchar(50), serverproperty('Collation')) AS COLLATION, CONVERT(nvarchar(50), serverproperty('ComputerNamePhysicalNetBIOS')) AS ComputerNamePhysicalNetBIOS, - CONVERT(nvarchar(50), serverproperty('ComputerNamePhysicalNetBIOS')) AS 'SqlHost' + CONVERT(nvarchar(50), serverproperty('ComputerNamePhysicalNetBIOS')) AS 'SqlHost' \ No newline at end of file diff --git a/SQL Queries/Data Warehouse/SQL_UserMapping_DW.sql b/SQL Queries/Data Warehouse/SQL_UserMapping_DW.sql index 9c2a9d4..ace6696 100644 --- a/SQL Queries/Data Warehouse/SQL_UserMapping_DW.sql +++ b/SQL Queries/Data Warehouse/SQL_UserMapping_DW.sql @@ -1,32 +1,32 @@ -DECLARE @DB_Users TABLE -(DBName sysname, UserName sysname, LoginType sysname, AssociatedRole varchar(max),create_date datetime,modify_date datetime) - -INSERT @DB_Users -EXEC sp_MSforeachdb - -' -use [?] -SELECT ''?'' AS DB_Name, -case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName, -prin.type_desc AS LoginType, -isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole ,create_date,modify_date -FROM sys.database_principals prin -LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id -WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and -prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%''' - -SELECT -dbname,username ,logintype ,create_date ,modify_date , -STUFF( -( -SELECT ',' + CONVERT(VARCHAR(500),associatedrole) -FROM @DB_Users user2 -WHERE -user1.DBName=user2.DBName AND user1.UserName=user2.UserName -FOR XML PATH('') -) -,1,1,'') AS Permissions_user -FROM @DB_Users user1 -GROUP BY -dbname,username ,logintype ,create_date ,modify_date -ORDER BY DBName, username +DECLARE @DB_Users TABLE +(DBName sysname, UserName sysname, LoginType sysname, AssociatedRole varchar(max),create_date datetime,modify_date datetime) + +INSERT @DB_Users +EXEC sp_MSforeachdb + +' +use [?] +SELECT ''?'' AS DB_Name, +case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName, +prin.type_desc AS LoginType, +isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole ,create_date,modify_date +FROM sys.database_principals prin +LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id +WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and +prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%''' + +SELECT +dbname,username ,logintype ,create_date ,modify_date , +STUFF( +( +SELECT ',' + CONVERT(VARCHAR(500),associatedrole) +FROM @DB_Users user2 +WHERE +user1.DBName=user2.DBName AND user1.UserName=user2.UserName +FOR XML PATH('') +) +,1,1,'') AS Permissions_user +FROM @DB_Users user1 +GROUP BY +dbname,username ,logintype ,create_date ,modify_date +ORDER BY DBName, username \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Alerts_ByCount.sql b/SQL Queries/OperationsManager/Alerts_ByCount.sql index c01cd55..1f6526b 100644 --- a/SQL Queries/OperationsManager/Alerts_ByCount.sql +++ b/SQL Queries/OperationsManager/Alerts_ByCount.sql @@ -1,4 +1,4 @@ -SELECT TOP 20 SUM(1) AS AlertCount, AlertStringName, AlertStringDescription, MonitoringRuleId, Name +SELECT TOP 50 SUM(1) AS AlertCount, AlertStringName, AlertStringDescription, MonitoringRuleId, Name FROM Alertview WITH (NOLOCK) WHERE TimeRaised is not NULL GROUP BY AlertStringName, AlertStringDescription, MonitoringRuleId, Name diff --git a/SQL Queries/OperationsManager/Alerts_ByDay.sql b/SQL Queries/OperationsManager/Alerts_ByDay.sql index 843ae38..f4ac67d 100644 --- a/SQL Queries/OperationsManager/Alerts_ByDay.sql +++ b/SQL Queries/OperationsManager/Alerts_ByDay.sql @@ -1,5 +1,5 @@ -SELECT CONVERT(VARCHAR(20), TimeAdded, 102) AS DayAdded, COUNT(*) AS NumAlertsPerDay +SELECT TOP 7 CONVERT(VARCHAR(20), TimeAdded, 102) AS DayAdded, COUNT(*) AS NumAlertsPerDay FROM AlertView WHERE TimeRaised is not NULL GROUP BY CONVERT(VARCHAR(20), TimeAdded, 102) -ORDER BY DayAdded DESC +ORDER BY DayAdded DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Alerts_ByOldest.sql b/SQL Queries/OperationsManager/Alerts_ByOldest.sql index 07f2529..f7078c9 100644 --- a/SQL Queries/OperationsManager/Alerts_ByOldest.sql +++ b/SQL Queries/OperationsManager/Alerts_ByOldest.sql @@ -1,12 +1,12 @@ -SELECT TOP 20 DATEDIFF(Day,TimeRaised,current_timestamp) AS DaysOpened, Case Severity -When 0 then 'Information' -When 1 then 'Warning' -When 2 then 'Critical' -End as [Severity],RepeatCount, AlertStringName, AlertStringDescription, MonitoringObjectDisplayName, MonitoringRuleId, Name, AlertParams, Case ResolutionState -When 0 then 'Open' -End as [ResolutionState] -FROM Alertview WITH (NOLOCK) -WHERE Timeraised is not NULL -AND ResolutionState = 0 -GROUP BY AlertStringName, RepeatCount, TimeRaised, Severity, MonitoringObjectDisplayName, Lastmodified,AlertStringDescription, AlertParams, MonitoringRuleId, Name, ResolutionState -ORDER BY DaysOpened DESC, RepeatCount DESC +SELECT TOP 50 DATEDIFF(Day,TimeRaised,current_timestamp) AS DaysOpened, Case Severity +When 0 then 'Information' +When 1 then 'Warning' +When 2 then 'Critical' +End as [Severity],RepeatCount, AlertStringName, AlertStringDescription, MonitoringObjectDisplayName, MonitoringRuleId, Name, AlertParams, Case ResolutionState +When 0 then 'Open' +End as [ResolutionState] +FROM Alertview WITH (NOLOCK) +WHERE Timeraised is not NULL +AND ResolutionState = 0 +GROUP BY AlertStringName, RepeatCount, TimeRaised, Severity, MonitoringObjectDisplayName, Lastmodified,AlertStringDescription, AlertParams, MonitoringRuleId, Name, ResolutionState +ORDER BY DaysOpened DESC, RepeatCount DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Alerts_ByRepeat.sql b/SQL Queries/OperationsManager/Alerts_ByRepeat.sql index d126cb9..5431977 100644 --- a/SQL Queries/OperationsManager/Alerts_ByRepeat.sql +++ b/SQL Queries/OperationsManager/Alerts_ByRepeat.sql @@ -1,5 +1,5 @@ -SELECT TOP 20 RepeatCount, AlertStringName, AlertStringDescription, MonitoringRuleId, Name +SELECT TOP 50 RepeatCount, AlertStringName, AlertStringDescription, MonitoringRuleId, Name FROM Alertview WITH (NOLOCK) WHERE Timeraised is not NULL GROUP BY AlertStringName, RepeatCount, AlertStringDescription, MonitoringRuleId, Name -ORDER BY RepeatCount DESC +ORDER BY RepeatCount DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Broken_Relationships.sql b/SQL Queries/OperationsManager/Broken_Relationships.sql index dda5b6f..8a079b7 100644 --- a/SQL Queries/OperationsManager/Broken_Relationships.sql +++ b/SQL Queries/OperationsManager/Broken_Relationships.sql @@ -1,14 +1,14 @@ ----Check for Broken Relationship -SELECT R.[RelationshipId], - RT.[RelationshipTypeId], - S.[FullName] as SourceName, - T.[FullName] as TargetName -FROM dbo.[Relationship] R with (nolock) - INNER JOIN dbo.[RelationshipType] RT with (nolock) - ON RT.[RelationshipTypeId] = R.[RelationshipTypeId] - INNER JOIN dbo.[BaseManagedEntity] S with (nolock) - ON S.[BaseManagedEntityId] = R.[SourceEntityId] - INNER JOIN dbo.[BaseManagedEntity] T with (nolock) - ON T.[BaseManagedEntityId] = R.[TargetEntityId] -WHERE R.[IsDeleted] = 0 - AND (S.[IsDeleted] = 1 OR T.[IsDeleted] = 1) +---Check for Broken Relationship +SELECT R.[RelationshipId], + RT.[RelationshipTypeId], + S.[FullName] as SourceName, + T.[FullName] as TargetName +FROM dbo.[Relationship] R with (nolock) + INNER JOIN dbo.[RelationshipType] RT with (nolock) + ON RT.[RelationshipTypeId] = R.[RelationshipTypeId] + INNER JOIN dbo.[BaseManagedEntity] S with (nolock) + ON S.[BaseManagedEntityId] = R.[SourceEntityId] + INNER JOIN dbo.[BaseManagedEntity] T with (nolock) + ON T.[BaseManagedEntityId] = R.[TargetEntityId] +WHERE R.[IsDeleted] = 0 + AND (S.[IsDeleted] = 1 OR T.[IsDeleted] = 1) \ No newline at end of file diff --git a/SQL Queries/OperationsManager/ConfigChurn_OpsDB.sql b/SQL Queries/OperationsManager/ConfigChurn_OpsDB.sql index 08acd28..b30690c 100644 --- a/SQL Queries/OperationsManager/ConfigChurn_OpsDB.sql +++ b/SQL Queries/OperationsManager/ConfigChurn_OpsDB.sql @@ -33,4 +33,4 @@ HAVING COUNT(*) ) > 10 order by - [Number of changes] DESC, LanguageCode DESC + [Number of changes] DESC, LanguageCode DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Configuration_OpsDB.sql b/SQL Queries/OperationsManager/Configuration_OpsDB.sql index ddd400e..ccf1b1e 100644 --- a/SQL Queries/OperationsManager/Configuration_OpsDB.sql +++ b/SQL Queries/OperationsManager/Configuration_OpsDB.sql @@ -1,11 +1,11 @@ -SELECT - ManagedTypePropertyName, - SettingValue, - mtv.DisplayName, - gs.LastModified -FROM - GlobalSettings gs WITH (NOLOCK) - INNER JOIN ManagedTypeProperty mtp WITH (NOLOCK) on gs.ManagedTypePropertyId = mtp.ManagedTypePropertyId - INNER JOIN ManagedTypeView mtv on mtp.ManagedTypeId = mtv.Id -ORDER BY +SELECT + ManagedTypePropertyName, + SettingValue, + mtv.DisplayName, + gs.LastModified +FROM + GlobalSettings gs WITH (NOLOCK) + INNER JOIN ManagedTypeProperty mtp WITH (NOLOCK) on gs.ManagedTypePropertyId = mtp.ManagedTypePropertyId + INNER JOIN ManagedTypeView mtv on mtp.ManagedTypeId = mtv.Id +ORDER BY mtv.DisplayName \ No newline at end of file diff --git a/SQL Queries/OperationsManager/CriticalState_Monitors.sql b/SQL Queries/OperationsManager/CriticalState_Monitors.sql index 68d5974..e7b9019 100644 --- a/SQL Queries/OperationsManager/CriticalState_Monitors.sql +++ b/SQL Queries/OperationsManager/CriticalState_Monitors.sql @@ -1,15 +1,15 @@ ---List of all monitors in a critical state - -SELECT -mv.DisplayName AS 'MonitorDisplayName', -mv.Name AS 'MonitorName', -bme.Path, -bme.DisplayName, -bme.FullName AS 'Target', -s.LastModified AS 'StateLastModified' -FROM State s -JOIN BaseManagedEntity bme WITH (NOLOCK) ON s.BaseManagedEntityId = bme.BaseManagedEntityId -JOIN MonitorView mv ON mv.Id = s.MonitorId -WHERE s.HealthState = 3 -AND mv.IsUnitMonitor = 1 +--List of all monitors in a critical state + +SELECT +mv.DisplayName AS 'MonitorDisplayName', +mv.Name AS 'MonitorName', +bme.Path, +bme.DisplayName, +bme.FullName AS 'Target', +s.LastModified AS 'StateLastModified' +FROM State s +JOIN BaseManagedEntity bme WITH (NOLOCK) ON s.BaseManagedEntityId = bme.BaseManagedEntityId +JOIN MonitorView mv ON mv.Id = s.MonitorId +WHERE s.HealthState = 3 +AND mv.IsUnitMonitor = 1 ORDER BY mv.DisplayName \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Discoveries.sql b/SQL Queries/OperationsManager/Discoveries.sql index 60d03ca..367686b 100644 --- a/SQL Queries/OperationsManager/Discoveries.sql +++ b/SQL Queries/OperationsManager/Discoveries.sql @@ -1,14 +1,14 @@ -SELECT -d.DiscoveryId, -d.DiscoveryName, -mpv.FriendlyName as 'MPDisplayName', -d.DiscoveryAccessibility, -REPLACE(REPLACE(REPLACE(d.DiscoveryEnabled, '4', 'True'),'0', 'False'), '3', 'onEssentialMonitoring') as 'DiscoveryEnabled', -CASE WHEN bme.DisplayName IS NULL then mt.TypeName else bme.DisplayName END as 'DiscoveryTarget', -REPLACE(REPLACE(d.DiscoveryConfirmDelivery, 0, 'False'), '1', 'True') as 'DiscoveryConfirmDelivery', -REPLACE(REPLACE(d.DiscoveryRemotable, 0, 'False'),'1', 'True') as 'DiscoveryRemotable', -d.TimeAdded -FROM Discovery AS d WITH (NOLOCK) LEFT JOIN -ManagementPackView AS mpv ON d.ManagementPackId = mpv.Id LEFT JOIN -BaseManagedEntity AS bme WITH (NOLOCK) ON d.DiscoveryTarget = bme.BaseManagedEntityId LEFT JOIN +SELECT +d.DiscoveryId, +d.DiscoveryName, +mpv.FriendlyName as 'MPDisplayName', +d.DiscoveryAccessibility, +REPLACE(REPLACE(REPLACE(d.DiscoveryEnabled, '4', 'True'),'0', 'False'), '3', 'onEssentialMonitoring') as 'DiscoveryEnabled', +CASE WHEN bme.DisplayName IS NULL then mt.TypeName else bme.DisplayName END as 'DiscoveryTarget', +REPLACE(REPLACE(d.DiscoveryConfirmDelivery, 0, 'False'), '1', 'True') as 'DiscoveryConfirmDelivery', +REPLACE(REPLACE(d.DiscoveryRemotable, 0, 'False'),'1', 'True') as 'DiscoveryRemotable', +d.TimeAdded +FROM Discovery AS d WITH (NOLOCK) LEFT JOIN +ManagementPackView AS mpv ON d.ManagementPackId = mpv.Id LEFT JOIN +BaseManagedEntity AS bme WITH (NOLOCK) ON d.DiscoveryTarget = bme.BaseManagedEntityId LEFT JOIN ManagedType AS mt WITH (NOLOCK) ON d.DiscoveryTarget = mt.ManagedTypeId \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Event29181_CastNotValid.sql b/SQL Queries/OperationsManager/Event29181_CastNotValid.sql index 9e2e626..cfa7112 100644 --- a/SQL Queries/OperationsManager/Event29181_CastNotValid.sql +++ b/SQL Queries/OperationsManager/Event29181_CastNotValid.sql @@ -1,26 +1,26 @@ -select - DiscoveryName, - MPName, - MPFriendlyName, - MPVersion, - MPIsSealed, - MPLastModified, - MPCreated, - PrincipalName -from - discovery d - join - ManagementPack MP - on MP.ManagementPackId = d.ManagementPackId - join - DiscoverySource DS - on DS.DiscoveryRuleId = d.DiscoveryId - join - DiscoverySourceToTypedManagedEntity DSTME - on DSTME.DiscoverySourceId = DS.DiscoverySourceId - join - MTV_HealthService MHS - on MHS.BaseManagedEntityId = DSTME.TypedManagedEntityId -where - MaximumQueueSize is null +select + DiscoveryName, + MPName, + MPFriendlyName, + MPVersion, + MPIsSealed, + MPLastModified, + MPCreated, + PrincipalName +from + discovery d + join + ManagementPack MP + on MP.ManagementPackId = d.ManagementPackId + join + DiscoverySource DS + on DS.DiscoveryRuleId = d.DiscoveryId + join + DiscoverySourceToTypedManagedEntity DSTME + on DSTME.DiscoverySourceId = DS.DiscoverySourceId + join + MTV_HealthService MHS + on MHS.BaseManagedEntityId = DSTME.TypedManagedEntityId +where + MaximumQueueSize is null or DisplayName = '' \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Event29181_System.DBNull-Continued.sql b/SQL Queries/OperationsManager/Event29181_System.DBNull-Continued.sql index 6e3833b..b752dc2 100644 --- a/SQL Queries/OperationsManager/Event29181_System.DBNull-Continued.sql +++ b/SQL Queries/OperationsManager/Event29181_System.DBNull-Continued.sql @@ -1,36 +1,36 @@ -declare @DiscoverySourceId uniqueidentifier; -declare @TimeGenerated datetime; -set - @TimeGenerated = GETUTCDATE(); -set - @DiscoverySourceId = dbo.fn_DiscoverySourceId_User(); -SELECT - TME.[TypedManagedEntityid] -FROM - MTV_HealthService HS - INNER JOIN - dbo.[BaseManagedEntity] BHS - ON BHS.[BaseManagedEntityId] = HS.[BaseManagedEntityId] - INNER JOIN - dbo.[TypedManagedEntity] TME - ON TME.[BaseManagedEntityId] = BHS.[TopLevelHostEntityId] - AND TME.[IsDeleted] = 0 - INNER JOIN - dbo.[DerivedManagedTypes] DMT - ON DMT.[DerivedTypeId] = TME.[ManagedTypeId] - INNER JOIN - dbo.[ManagedType] BT - ON DMT.[BaseTypeId] = BT.[ManagedTypeId] - AND BT.[TypeName] = N'Microsoft.Windows.Computer' - LEFT OUTER JOIN - dbo.Relationship HSC - ON HSC.[SourceEntityId] = HS.[BaseManagedEntityId] - AND HSC.[RelationshipTypeId] = dbo.fn_RelationshipTypeId_HealthServiceCommunication() - AND HSC.[IsDeleted] = 0 - INNER JOIN - DiscoverySourceToTypedManagedEntity DSTME - ON DSTME.[TypedManagedEntityId] = TME.[TypedManagedEntityId] - AND DSTME.[DiscoverySourceId] = @DiscoverySourceId -WHERE - HS.[IsAgent] = 1 +declare @DiscoverySourceId uniqueidentifier; +declare @TimeGenerated datetime; +set + @TimeGenerated = GETUTCDATE(); +set + @DiscoverySourceId = dbo.fn_DiscoverySourceId_User(); +SELECT + TME.[TypedManagedEntityid] +FROM + MTV_HealthService HS + INNER JOIN + dbo.[BaseManagedEntity] BHS + ON BHS.[BaseManagedEntityId] = HS.[BaseManagedEntityId] + INNER JOIN + dbo.[TypedManagedEntity] TME + ON TME.[BaseManagedEntityId] = BHS.[TopLevelHostEntityId] + AND TME.[IsDeleted] = 0 + INNER JOIN + dbo.[DerivedManagedTypes] DMT + ON DMT.[DerivedTypeId] = TME.[ManagedTypeId] + INNER JOIN + dbo.[ManagedType] BT + ON DMT.[BaseTypeId] = BT.[ManagedTypeId] + AND BT.[TypeName] = N'Microsoft.Windows.Computer' + LEFT OUTER JOIN + dbo.Relationship HSC + ON HSC.[SourceEntityId] = HS.[BaseManagedEntityId] + AND HSC.[RelationshipTypeId] = dbo.fn_RelationshipTypeId_HealthServiceCommunication() + AND HSC.[IsDeleted] = 0 + INNER JOIN + DiscoverySourceToTypedManagedEntity DSTME + ON DSTME.[TypedManagedEntityId] = TME.[TypedManagedEntityId] + AND DSTME.[DiscoverySourceId] = @DiscoverySourceId +WHERE + HS.[IsAgent] = 1 AND HSC.[RelationshipId] IS NULL; \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Event29181_System.DBNull.sql b/SQL Queries/OperationsManager/Event29181_System.DBNull.sql index e1cbab8..59e8403 100644 --- a/SQL Queries/OperationsManager/Event29181_System.DBNull.sql +++ b/SQL Queries/OperationsManager/Event29181_System.DBNull.sql @@ -1,13 +1,13 @@ -SELECT - PrincipalName, - DisplayName, - MaximumQueueSize, - IsManagementServer, - IsGateway, - HeartbeatEnabled, - HeartbeatInterval, - Port -FROM - MTV_HealthService -where +SELECT + PrincipalName, + DisplayName, + MaximumQueueSize, + IsManagementServer, + IsGateway, + HeartbeatEnabled, + HeartbeatInterval, + Port +FROM + MTV_HealthService +where PrincipalName IS NULL \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Events_ByComputer.sql b/SQL Queries/OperationsManager/Events_ByComputer.sql index 0954291..70b56c5 100644 --- a/SQL Queries/OperationsManager/Events_ByComputer.sql +++ b/SQL Queries/OperationsManager/Events_ByComputer.sql @@ -2,4 +2,4 @@ SELECT top 20 LoggingComputer as ComputerName, COUNT(*) AS TotalEvents, Number a FROM EventallView eav with (NOLOCK) LEFT JOIN RuleView rv with (NOLOCK) on rv.Id = eav.RuleId GROUP BY LoggingComputer, Number, Name, DisplayName -ORDER BY TotalEvents DESC +ORDER BY TotalEvents DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Events_ByNumber.sql b/SQL Queries/OperationsManager/Events_ByNumber.sql index e603f05..1cf6824 100644 --- a/SQL Queries/OperationsManager/Events_ByNumber.sql +++ b/SQL Queries/OperationsManager/Events_ByNumber.sql @@ -1,6 +1,8 @@ SELECT top 50 Number as EventID, COUNT(*) AS TotalEvents, - Publishername as EventSource -FROM EventAllView WITH (NOLOCK) -GROUP BY Number, Publishername + Publishername as EventSource, + Name as RuleName, DisplayName as RuleDisplayName +FROM EventAllView eav WITH (NOLOCK) +LEFT JOIN RuleView rv with (NOLOCK) on rv.Id = eav.RuleId +GROUP BY Number, Publishername, Name, DisplayName ORDER BY TotalEvents DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Grooming_Logs_OpsDB.sql b/SQL Queries/OperationsManager/Grooming_Logs_OpsDB.sql index cac0fbd..24a00fd 100644 --- a/SQL Queries/OperationsManager/Grooming_Logs_OpsDB.sql +++ b/SQL Queries/OperationsManager/Grooming_Logs_OpsDB.sql @@ -5,4 +5,4 @@ TimeStarted, TimeFinished, DATEDIFF (second,TimeStarted,TimeFinished) AS 'DurationSeconds' from InternalJobHistory WITH (NOLOCK) -order by InternalJobHistoryId DESC +order by InternalJobHistoryId DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/HealthService_Heartbeat.sql b/SQL Queries/OperationsManager/HealthService_Heartbeat.sql index 1560aa9..4b7a98f 100644 --- a/SQL Queries/OperationsManager/HealthService_Heartbeat.sql +++ b/SQL Queries/OperationsManager/HealthService_Heartbeat.sql @@ -1,8 +1,8 @@ -SELECT bme.DisplayName AS 'AgentName', -s.LastModified as 'LastModifiedUTC' -FROM state AS s, BaseManagedEntity AS bme WITH (NOLOCK) -WHERE s.basemanagedentityid = bme.basemanagedentityid -AND s.monitorid -IN (SELECT MonitorId FROM Monitor WITH (NOLOCK) WHERE MonitorName = 'Microsoft.SystemCenter.HealthService.Heartbeat') -AND s.Healthstate = '3' AND bme.IsDeleted = '0' +SELECT bme.DisplayName AS 'AgentName', +s.LastModified as 'LastModifiedUTC' +FROM state AS s, BaseManagedEntity AS bme WITH (NOLOCK) +WHERE s.basemanagedentityid = bme.basemanagedentityid +AND s.monitorid +IN (SELECT MonitorId FROM Monitor WITH (NOLOCK) WHERE MonitorName = 'Microsoft.SystemCenter.HealthService.Heartbeat') +AND s.Healthstate = '3' AND bme.IsDeleted = '0' ORDER BY s.Lastmodified DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/HealthService_Inventory.sql b/SQL Queries/OperationsManager/HealthService_Inventory.sql index 6b9b681..d18412b 100644 --- a/SQL Queries/OperationsManager/HealthService_Inventory.sql +++ b/SQL Queries/OperationsManager/HealthService_Inventory.sql @@ -22,4 +22,4 @@ FROM MTV_HealthService HS WITH (NOLOCK) JOIN Relationship R WITH (NOLOCK) ON R.SourceEntityId = HS.BaseManagedEntityId JOIN BaseManagedEntity TargetBME WITH (NOLOCK) ON R.TargetEntityId = TargetBME.BaseManagedEntityId WHERE R.IsDeleted = 0 AND R.RelationshipTypeId = dbo.fn_ManagedTypeId_MicrosoftSystemCenterHealthServiceCommunication() -ORDER BY [HealthService],[PrimaryManagementServer] +ORDER BY [HealthService],[PrimaryManagementServer] \ No newline at end of file diff --git a/SQL Queries/OperationsManager/HealthService_LastContact.sql b/SQL Queries/OperationsManager/HealthService_LastContact.sql index 493879b..9d2bc86 100644 --- a/SQL Queries/OperationsManager/HealthService_LastContact.sql +++ b/SQL Queries/OperationsManager/HealthService_LastContact.sql @@ -1,32 +1,32 @@ --- This script queries the database for any agents missing a heartbeat, and letting us know their last contact date/time --- Original Script found here: https://docs.microsoft.com/en-us/archive/blogs/mariussutara/last-contacted-better-sql-query - -declare @substract float -declare @numberOfMissing float -declare @interval float - --- Get the number of missing heartbeats -select @numberOfMissing = SettingValue from GlobalSettings GS -join ManagedTypeProperty MTP with(nolock) on GS.ManagedTypePropertyId = MTP.ManagedTypePropertyId -where MTP.ManagedTypePropertyName = 'NumberOfMissingHeartBeatsToMarkMachineDown' - --- Get the heartbeat interval -select @interval = SettingValue from GlobalSettings GS -join ManagedTypeProperty MTP with(nolock) on GS.ManagedTypePropertyId = MTP.ManagedTypePropertyId -where MTP.ManagedTypePropertyName = 'HeartbeatInterval' - --- Calculate the amount of lapsed time before a system is marked as non contactable -select @substract = (@numberOfMissing * @interval)/100000 -select B.DisplayName, AH.TimeStarted, (cast((cast(tmp.MaxTimeStarted as float)- @substract) as datetime)) as [ApproxLastContactedTime (UTC)], -dateadd ( hh, +9, (cast((cast(tmp.MaxTimeStarted as float)- @substract) as datetime))) as 'ApproxLastContactedTime (Pacific)' from Availability A -join BaseManagedEntity B with(nolock) on B.BaseManagedEntityId = A.BaseManagedEntityId -join AvailabilityHistory AH with(nolock) on AH.BaseManagedEntityId = A.BaseManagedEntityId -join -( - select MAX(AHTMP.TimeStarted) AS MaxTimeStarted, BME.BaseManagedEntityId from AvailabilityHistory AHTMP - join BaseManagedEntity BME with(nolock) on BME.BaseManagedEntityId = AHTMP.BaseManagedEntityId - where BME.IsDeleted = 0 - group by BME.BaseManagedEntityId -) -TMP on AH.TimeStarted = MaxTimeStarted +-- This script queries the database for any agents missing a heartbeat, and letting us know their last contact date/time +-- Original Script found here: https://docs.microsoft.com/en-us/archive/blogs/mariussutara/last-contacted-better-sql-query + +declare @substract float +declare @numberOfMissing float +declare @interval float + +-- Get the number of missing heartbeats +select @numberOfMissing = SettingValue from GlobalSettings GS +join ManagedTypeProperty MTP with(nolock) on GS.ManagedTypePropertyId = MTP.ManagedTypePropertyId +where MTP.ManagedTypePropertyName = 'NumberOfMissingHeartBeatsToMarkMachineDown' + +-- Get the heartbeat interval +select @interval = SettingValue from GlobalSettings GS +join ManagedTypeProperty MTP with(nolock) on GS.ManagedTypePropertyId = MTP.ManagedTypePropertyId +where MTP.ManagedTypePropertyName = 'HeartbeatInterval' + +-- Calculate the amount of lapsed time before a system is marked as non contactable +select @substract = (@numberOfMissing * @interval)/100000 +select B.DisplayName, AH.TimeStarted, (cast((cast(tmp.MaxTimeStarted as float)- @substract) as datetime)) as [ApproxLastContactedTime (UTC)], +dateadd ( hh, +9, (cast((cast(tmp.MaxTimeStarted as float)- @substract) as datetime))) as 'ApproxLastContactedTime (Pacific)' from Availability A +join BaseManagedEntity B with(nolock) on B.BaseManagedEntityId = A.BaseManagedEntityId +join AvailabilityHistory AH with(nolock) on AH.BaseManagedEntityId = A.BaseManagedEntityId +join +( + select MAX(AHTMP.TimeStarted) AS MaxTimeStarted, BME.BaseManagedEntityId from AvailabilityHistory AHTMP + join BaseManagedEntity BME with(nolock) on BME.BaseManagedEntityId = AHTMP.BaseManagedEntityId + where BME.IsDeleted = 0 + group by BME.BaseManagedEntityId +) +TMP on AH.TimeStarted = MaxTimeStarted where A.IsAvailable = 0 and B.IsDeleted = 0 \ No newline at end of file diff --git a/SQL Queries/OperationsManager/HealthService_Pending.sql b/SQL Queries/OperationsManager/HealthService_Pending.sql index de20a6f..cda0feb 100644 --- a/SQL Queries/OperationsManager/HealthService_Pending.sql +++ b/SQL Queries/OperationsManager/HealthService_Pending.sql @@ -1,15 +1,15 @@ -SELECT -AgentPendingActionId, -AgentName, -ManagementServerName, -Case PendingActionType -When 0 then 'Manual Approval' -When 1 then 'Push Install' -When 2 then 'Updated Needed' -When 10 then 'Repair Failed' -When 17 then 'Push Install Failed' -When 18 then 'Update Failed' -End as [PendingActionType], -PendingActionData, -LastModified -FROM AgentPendingAction WITH (NOLOCK) +SELECT +AgentPendingActionId, +AgentName, +ManagementServerName, +Case PendingActionType +When 0 then 'Manual Approval' +When 1 then 'Push Install' +When 2 then 'Updated Needed' +When 10 then 'Repair Failed' +When 17 then 'Push Install Failed' +When 18 then 'Update Failed' +End as [PendingActionType], +PendingActionData, +LastModified +FROM AgentPendingAction WITH (NOLOCK) \ No newline at end of file diff --git a/SQL Queries/OperationsManager/HeathService_Avail_Last_7days.sql b/SQL Queries/OperationsManager/HeathService_Avail_Last_7days.sql index 4915fb8..d8203fc 100644 --- a/SQL Queries/OperationsManager/HeathService_Avail_Last_7days.sql +++ b/SQL Queries/OperationsManager/HeathService_Avail_Last_7days.sql @@ -1,21 +1,21 @@ --- Get only changes made in the last 7 days to the AvailabilityHistory Table -select BME.Path, -Case AV.ReasonCode -When 0 then 'Unknown' -When 1 then 'Unavailable - No heartbeat' -When 17 then 'Connector Service Paused' -When 25 then 'Action Account Issue' -When 41 then 'Config Data Handling Issue' -When 42 then 'Config Data Loading Issue' -When 43 then 'System Workflows Unloaded' -When 49 then 'Entity State Collection Stalled' -When 50 then 'Monitor State Collection Stalled' -When 51 then 'Alert Collection Stalled' -When 97 then 'Solution Event Source Not Open' -When 98 then 'Cannot Parse Config' -End as [Reason for Change], -AV.TimeStarted, -AV.TimeFinished from AvailabilityHistory AV WITH (NOLOCK) -join BaseManagedEntity BME WITH (NOLOCK) on AV.BaseManagedEntityId=BME.BaseManagedEntityId -WHERE AV.TimeStarted > DATEADD(day, -7, GETUTCDATE()) +-- Get only changes made in the last 7 days to the AvailabilityHistory Table +select BME.Path, +Case AV.ReasonCode +When 0 then 'Unknown' +When 1 then 'Unavailable - No heartbeat' +When 17 then 'Connector Service Paused' +When 25 then 'Action Account Issue' +When 41 then 'Config Data Handling Issue' +When 42 then 'Config Data Loading Issue' +When 43 then 'System Workflows Unloaded' +When 49 then 'Entity State Collection Stalled' +When 50 then 'Monitor State Collection Stalled' +When 51 then 'Alert Collection Stalled' +When 97 then 'Solution Event Source Not Open' +When 98 then 'Cannot Parse Config' +End as [Reason for Change], +AV.TimeStarted, +AV.TimeFinished from AvailabilityHistory AV WITH (NOLOCK) +join BaseManagedEntity BME WITH (NOLOCK) on AV.BaseManagedEntityId=BME.BaseManagedEntityId +WHERE AV.TimeStarted > DATEADD(day, -7, GETUTCDATE()) order by AV.TimeStarted desc \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Index_Maintenance_OpsDB.sql b/SQL Queries/OperationsManager/Index_Maintenance_OpsDB.sql index 33d9a4e..84b9616 100644 --- a/SQL Queries/OperationsManager/Index_Maintenance_OpsDB.sql +++ b/SQL Queries/OperationsManager/Index_Maintenance_OpsDB.sql @@ -1,16 +1,16 @@ -SELECT dtioh.OptimizationDurationSeconds AS 'DurationSeconds', -dt.TableName, -'Reindex' AS 'OperationType', -dtioh.OptimizationStartDateTime AS 'StartTime' -FROM DomainTableIndexOptimizationHistory dtioh -JOIN DomainTable dt ON dt.DomainTableRowId = dtioh.DomainTableIndexRowId -WHERE dtioh.OptimizationDurationSeconds > 0 -UNION ALL -SELECT dtsuh.UpdateDurationSeconds AS 'DurationSeconds', -dt.TableName, -'Statistics' AS 'OperationType', -dtsuh.UpdateStartDateTime AS 'StartTime' -FROM DomainTableStatisticsUpdateHistory dtsuh -JOIN DomainTable dt ON dt.DomainTableRowId = dtsuh.DomainTableRowId -WHERE dtsuh.UpdateDurationSeconds > 0 +SELECT dtioh.OptimizationDurationSeconds AS 'DurationSeconds', +dt.TableName, +'Reindex' AS 'OperationType', +dtioh.OptimizationStartDateTime AS 'StartTime' +FROM DomainTableIndexOptimizationHistory dtioh +JOIN DomainTable dt ON dt.DomainTableRowId = dtioh.DomainTableIndexRowId +WHERE dtioh.OptimizationDurationSeconds > 0 +UNION ALL +SELECT dtsuh.UpdateDurationSeconds AS 'DurationSeconds', +dt.TableName, +'Statistics' AS 'OperationType', +dtsuh.UpdateStartDateTime AS 'StartTime' +FROM DomainTableStatisticsUpdateHistory dtsuh +JOIN DomainTable dt ON dt.DomainTableRowId = dtsuh.DomainTableRowId +WHERE dtsuh.UpdateDurationSeconds > 0 ORDER BY DurationSeconds DESC, StartTime DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Instances_Hosted_AMSRP.sql b/SQL Queries/OperationsManager/Instances_Hosted_AMSRP.sql index af09de9..883dda7 100644 --- a/SQL Queries/OperationsManager/Instances_Hosted_AMSRP.sql +++ b/SQL Queries/OperationsManager/Instances_Hosted_AMSRP.sql @@ -1,4 +1,4 @@ -SELECT TargetObjectDisplayName, TargetObjectFullName -FROM RelationshipGenericView -WHERE SourceObjectDisplayName = 'All Management Servers Resource Pool' +SELECT TargetObjectDisplayName, TargetObjectFullName +FROM RelationshipGenericView +WHERE SourceObjectDisplayName = 'All Management Servers Resource Pool' ORDER BY TargetObjectFullName,TargetObjectDisplayName \ No newline at end of file diff --git a/SQL Queries/OperationsManager/MG_Overview.sql b/SQL Queries/OperationsManager/MG_Overview.sql index 8e3ee23..14403af 100644 --- a/SQL Queries/OperationsManager/MG_Overview.sql +++ b/SQL Queries/OperationsManager/MG_Overview.sql @@ -8,4 +8,4 @@ FROM (SELECT ManagementGroupName AS 'MG_Name' FROM __MOMManagementGroupInfo__) A (SELECT COUNT(*) AS 'Agent_Count' FROM MTV_HealthService WHERE IsManagementServer = 0 AND IsGateway = 0) AS Agent_Count, (SELECT COUNT(*) AS 'Agent_Pending' FROM AgentPendingAction) AS Agent_Pending, (SELECT COUNT(*) AS 'Unix_Count' FROM MTV_Microsoft$Unix$Computer) AS Unix_Count, -(SELECT Count(*) AS 'NetworkDevice_Count' FROM MTV_System$NetworkManagement$Node) AS NetworkDevice_Count \ No newline at end of file +(SELECT COUNT(*) AS 'NetworkDevice_Count' FROM MTV_System$NetworkManagement$Node) AS NetworkDevice_Count \ No newline at end of file diff --git a/SQL Queries/OperationsManager/MG_SQLPatchVersion_OpsDB.sql b/SQL Queries/OperationsManager/MG_SQLPatchVersion_OpsDB.sql index bb2ef2d..15728a3 100644 --- a/SQL Queries/OperationsManager/MG_SQLPatchVersion_OpsDB.sql +++ b/SQL Queries/OperationsManager/MG_SQLPatchVersion_OpsDB.sql @@ -1,2 +1,2 @@ --- Get the OpsMgr Update Rollup Version. +-- Get the OpsMgr Update Rollup Version. select * from [dbo].[SqlPatchVersion] WITH (NOLOCK) \ No newline at end of file diff --git a/SQL Queries/OperationsManager/MP_EventDescription_BadPractice.sql b/SQL Queries/OperationsManager/MP_EventDescription_BadPractice.sql index 83af1d5..d07706a 100644 --- a/SQL Queries/OperationsManager/MP_EventDescription_BadPractice.sql +++ b/SQL Queries/OperationsManager/MP_EventDescription_BadPractice.sql @@ -1,5 +1,5 @@ --- Instead of using EventDescription, follow the steps here: --- https://kevinholman.com/2008/04/22/using-event-description-as-criteria-for-a-rule/ -SELECT MPName, MPFriendlyName, CAST(MPXML AS xml) -FROM ManagementPack WITH (NOLOCK) +-- Instead of using EventDescription, follow the steps here: +-- https://kevinholman.com/2008/04/22/using-event-description-as-criteria-for-a-rule/ +SELECT MPName, MPFriendlyName, CAST(MPXML AS xml) +FROM ManagementPack WITH (NOLOCK) WHERE MPXML LIKE '%EventDescription%' AND MPFriendlyName != 'Apm.NTService' \ No newline at end of file diff --git a/SQL Queries/OperationsManager/MP_Removals.sql b/SQL Queries/OperationsManager/MP_Removals.sql index a46db9f..2472a5c 100644 --- a/SQL Queries/OperationsManager/MP_Removals.sql +++ b/SQL Queries/OperationsManager/MP_Removals.sql @@ -1,2 +1,2 @@ -SELECT * FROM MPRemovalLog WITH (NOLOCK) +SELECT * FROM MPRemovalLog WITH (NOLOCK) ORDER BY MPRemovalDate DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Maintenance_Mode.sql b/SQL Queries/OperationsManager/Maintenance_Mode.sql index 1369c4b..191a7f7 100644 --- a/SQL Queries/OperationsManager/Maintenance_Mode.sql +++ b/SQL Queries/OperationsManager/Maintenance_Mode.sql @@ -1,32 +1,32 @@ -SELECT -MM.BaseManagedEntityId, -FullName as [Object in Maintenance], -case MM.IsInMaintenanceMode -When 0 then 'False' -When 1 then 'True' -End as [Currently in Maintenance Mode], -StartTime as [Start Time], -ScheduledEndTime as [Scheduled End Time], -MM.[User] as [User], -Case ReasonCode -When 0 then 'Other (Planned)' -When 1 then 'Other (Unplanned)' -When 2 then 'Hardware: Maintenance (Planned)' -When 3 then 'Hardware: Maintenance (Unplanned)' -When 4 then 'Hardware: Installation (Planned)' -When 5 then 'Hardware: Installation (Unplanned)' -When 6 then 'Operating System: Reconfiguration (Planned)' -When 7 then 'Operating System: Reconfiguration (Unplanned)' -When 8 then 'Application: Maintenance (Planned)' -When 9 then 'Application: Maintenance (Unplanned)' -When 10 then 'Application: Installation (Planned)' -When 11 then 'Application: Unresponsive' -When 12 then 'Application: Unstable' -When 13 then 'Security issue' -When 14 then 'Loss of network connectivity (Unplanned)' -End as [Reason for Maintenance], -Comments -FROM BaseManagedEntity AS BME WITH (NOLOCK) INNER JOIN -MaintenanceMode AS MM WITH (NOLOCK) ON BME.BaseManagedEntityId = MM.BaseManagedEntityId ---INNER JOIN MT_Microsoft$SystemCenter$ManagementServer as MS WITH (NOLOCK) on BME.BaseManagedEntityId = MS.BaseManagedEntityId -ORDER BY [Start Time] DESC +SELECT +MM.BaseManagedEntityId, +FullName as [Object in Maintenance], +case MM.IsInMaintenanceMode +When 0 then 'False' +When 1 then 'True' +End as [Currently in Maintenance Mode], +StartTime as [Start Time], +ScheduledEndTime as [Scheduled End Time], +MM.[User] as [User], +Case ReasonCode +When 0 then 'Other (Planned)' +When 1 then 'Other (Unplanned)' +When 2 then 'Hardware: Maintenance (Planned)' +When 3 then 'Hardware: Maintenance (Unplanned)' +When 4 then 'Hardware: Installation (Planned)' +When 5 then 'Hardware: Installation (Unplanned)' +When 6 then 'Operating System: Reconfiguration (Planned)' +When 7 then 'Operating System: Reconfiguration (Unplanned)' +When 8 then 'Application: Maintenance (Planned)' +When 9 then 'Application: Maintenance (Unplanned)' +When 10 then 'Application: Installation (Planned)' +When 11 then 'Application: Unresponsive' +When 12 then 'Application: Unstable' +When 13 then 'Security issue' +When 14 then 'Loss of network connectivity (Unplanned)' +End as [Reason for Maintenance], +Comments +FROM BaseManagedEntity AS BME WITH (NOLOCK) INNER JOIN +MaintenanceMode AS MM WITH (NOLOCK) ON BME.BaseManagedEntityId = MM.BaseManagedEntityId +--INNER JOIN MT_Microsoft$SystemCenter$ManagementServer as MS WITH (NOLOCK) on BME.BaseManagedEntityId = MS.BaseManagedEntityId +ORDER BY [Start Time] DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Maintenance_Mode_ManagementServers.sql b/SQL Queries/OperationsManager/Maintenance_Mode_ManagementServers.sql index e7de08b..409fce1 100644 --- a/SQL Queries/OperationsManager/Maintenance_Mode_ManagementServers.sql +++ b/SQL Queries/OperationsManager/Maintenance_Mode_ManagementServers.sql @@ -1,32 +1,32 @@ -SELECT -MM.BaseManagedEntityId, -FullName as [Object in Maintenance], -case MM.IsInMaintenanceMode -When 0 then 'False' -When 1 then 'True' -End as [Currently in Maintenance Mode], -StartTime as [Start Time], -ScheduledEndTime as [Scheduled End Time], -MM.[User] as [User], -Case ReasonCode -When 0 then 'Other (Planned)' -When 1 then 'Other (Unplanned)' -When 2 then 'Hardware: Maintenance (Planned)' -When 3 then 'Hardware: Maintenance (Unplanned)' -When 4 then 'Hardware: Installation (Planned)' -When 5 then 'Hardware: Installation (Unplanned)' -When 6 then 'Operating System: Reconfiguration (Planned)' -When 7 then 'Operating System: Reconfiguration (Unplanned)' -When 8 then 'Application: Maintenance (Planned)' -When 9 then 'Application: Maintenance (Unplanned)' -When 10 then 'Application: Installation (Planned)' -When 11 then 'Application: Unresponsive' -When 12 then 'Application: Unstable' -When 13 then 'Security issue' -When 14 then 'Loss of network connectivity (Unplanned)' -End as [Reason for Maintenance], -Comments -FROM BaseManagedEntity AS BME WITH (NOLOCK) INNER JOIN -MaintenanceMode AS MM WITH (NOLOCK) ON BME.BaseManagedEntityId = MM.BaseManagedEntityId -INNER JOIN MT_Microsoft$SystemCenter$ManagementServer as MS WITH (NOLOCK) on BME.BaseManagedEntityId = MS.BaseManagedEntityId -ORDER BY [Start Time] DESC +SELECT +MM.BaseManagedEntityId, +FullName as [Object in Maintenance], +case MM.IsInMaintenanceMode +When 0 then 'False' +When 1 then 'True' +End as [Currently in Maintenance Mode], +StartTime as [Start Time], +ScheduledEndTime as [Scheduled End Time], +MM.[User] as [User], +Case ReasonCode +When 0 then 'Other (Planned)' +When 1 then 'Other (Unplanned)' +When 2 then 'Hardware: Maintenance (Planned)' +When 3 then 'Hardware: Maintenance (Unplanned)' +When 4 then 'Hardware: Installation (Planned)' +When 5 then 'Hardware: Installation (Unplanned)' +When 6 then 'Operating System: Reconfiguration (Planned)' +When 7 then 'Operating System: Reconfiguration (Unplanned)' +When 8 then 'Application: Maintenance (Planned)' +When 9 then 'Application: Maintenance (Unplanned)' +When 10 then 'Application: Installation (Planned)' +When 11 then 'Application: Unresponsive' +When 12 then 'Application: Unstable' +When 13 then 'Security issue' +When 14 then 'Loss of network connectivity (Unplanned)' +End as [Reason for Maintenance], +Comments +FROM BaseManagedEntity AS BME WITH (NOLOCK) INNER JOIN +MaintenanceMode AS MM WITH (NOLOCK) ON BME.BaseManagedEntityId = MM.BaseManagedEntityId +INNER JOIN MT_Microsoft$SystemCenter$ManagementServer as MS WITH (NOLOCK) on BME.BaseManagedEntityId = MS.BaseManagedEntityId +ORDER BY [Start Time] DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/ManagementPacks.sql b/SQL Queries/OperationsManager/ManagementPacks.sql index 7fcb08c..c5a6ae5 100644 --- a/SQL Queries/OperationsManager/ManagementPacks.sql +++ b/SQL Queries/OperationsManager/ManagementPacks.sql @@ -1,15 +1,15 @@ -select -mpv.Id, -mpv.DisplayName, -mpv.Name, -mpv.FriendlyName, -mpv.Version, -mpv.Sealed, -mpv.LastModified, -mpv.TimeCreated, -mpv.Description, -mpv.LanguageCode AS 'Language' ---CAST(mp.MPXML AS xml) AS 'XML' -from ManagementPackView mpv ---inner join ManagementPack mp WITH (NOLOCK) +select +mpv.Id, +mpv.DisplayName, +mpv.Name, +mpv.FriendlyName, +mpv.Version, +mpv.Sealed, +mpv.LastModified, +mpv.TimeCreated, +mpv.Description, +mpv.LanguageCode AS 'Language' +--CAST(mp.MPXML AS xml) AS 'XML' +from ManagementPackView mpv +--inner join ManagementPack mp WITH (NOLOCK) --on mpv.id = mp.ManagementPackId \ No newline at end of file diff --git a/SQL Queries/OperationsManager/ManagementServers.sql b/SQL Queries/OperationsManager/ManagementServers.sql index d2c4c76..099c6f6 100644 --- a/SQL Queries/OperationsManager/ManagementServers.sql +++ b/SQL Queries/OperationsManager/ManagementServers.sql @@ -1,20 +1,7 @@ -SELECT *, -Case ReasonCode -When 17 then 'The Health Service windows service is paused.' -When 25 then 'The Health Service Action Account is misconfigured or has invalid credentials.' -When 41 then 'The Health Service failed to parse the new configuration.' -When 42 then 'The Health Service failed to load the new configuration.' -When 43 then 'A System Rule failed to load.' -When 49 then 'Collection of Object State Change Events is stalled.' -When 50 then 'Collection of Monitor State Change Events is stalled.' -When 51 then 'Collection of Alerts is stalled.' -When 97 then 'The Health Service is unable to register with the Event Log Service. The Health Service cannot log additional Heartbeat and Connector events.' -When 98 then 'The Health Service is unable to parse configuration XML.' -When 1 then 'Reason Unknown. POSSIBLY due to Health Service not heartbeating within 3 minutes to SDK?' -End as [ReasonCodeResult] +-- Last Modified: +-- September 13th, 2022 - (blakedrumm@microsoft.com) Remove Reason Code Availability History and move to another TSQL Query. +SELECT * FROM MTV_HealthService mtv -LEFT JOIN AvailabilityHistory ahist -ON ahist.BaseManagedEntityId = mtv.BaseManagedEntityId WHERE mtv.IsManagementServer = 1 OR mtv.IsGateway = 1 -ORDER BY mtv.DisplayName +ORDER BY mtv.DisplayName \ No newline at end of file diff --git a/SQL Queries/OperationsManager/ManagementServers_Availability.sql b/SQL Queries/OperationsManager/ManagementServers_Availability.sql new file mode 100644 index 0000000..5fd07ce --- /dev/null +++ b/SQL Queries/OperationsManager/ManagementServers_Availability.sql @@ -0,0 +1,27 @@ +-- Last Modified: +-- September 13th, 2022 - (blakedrumm@microsoft.com) Seperate Availability History from ManagementServers.sql query. +SELECT mtv.BaseManagedEntityId, +mtv.DisplayName, +ahist.ReasonCode, +Case ahist.ReasonCode +When 17 then 'The Health Service windows service is paused.' +When 25 then 'The Health Service Action Account is misconfigured or has invalid credentials.' +When 41 then 'The Health Service failed to parse the new configuration.' +When 42 then 'The Health Service failed to load the new configuration.' +When 43 then 'A System Rule failed to load.' +When 49 then 'Collection of Object State Change Events is stalled.' +When 50 then 'Collection of Monitor State Change Events is stalled.' +When 51 then 'Collection of Alerts is stalled.' +When 97 then 'The Health Service is unable to register with the Event Log Service. The Health Service cannot log additional Heartbeat and Connector events.' +When 98 then 'The Health Service is unable to parse configuration XML.' +When 1 then 'Reason Unknown. POSSIBLY due to Health Service not heartbeating within 3 minutes to SDK?' +ELSE 'Unknown reason code.' +End as [ReasonCodeResult], +ahist.TimeStarted, +ahist.LastModified +FROM MTV_HealthService mtv +LEFT JOIN AvailabilityHistory ahist +ON ahist.BaseManagedEntityId = mtv.BaseManagedEntityId +WHERE mtv.IsManagementServer = 1 +OR mtv.IsGateway = 1 +ORDER BY mtv.DisplayName \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Notifications_Channels.sql b/SQL Queries/OperationsManager/Notifications_Channels.sql index 09287ee..43818fa 100644 --- a/SQL Queries/OperationsManager/Notifications_Channels.sql +++ b/SQL Queries/OperationsManager/Notifications_Channels.sql @@ -1,4 +1,4 @@ -exec sp_executesql N'-- ModuleTypesForNotifications -SELECT [ModuleTypeView].[Id],[ModuleTypeView].[Name],[ModuleTypeView].[ManagementPackId],[ModuleTypeView].[Accessibility],[ModuleTypeView].[OutputMonitoringDataTypeId],[ModuleTypeView].[Role],[ModuleTypeView].[CanGuaranteeDelivery],[ModuleTypeView].[IncludeSchemaTypes],[ModuleTypeView].[IsPassThrough],[ModuleTypeView].[IsStateful],[ModuleTypeView].[IsTriggerOnly],[ModuleTypeView].[Batching],[ModuleTypeView].[ImplementationXml],[ModuleTypeView].[ConfigurationXsd],[ModuleTypeView].[InputMonitoringDataTypes],[ModuleTypeView].[RunAs],[ModuleTypeView].[TimeAdded],[ModuleTypeView].[LastModified],[ModuleTypeView].[HasUIPageSet],[ModuleTypeView].[DisplayName],[ModuleTypeView].[Description],[ModuleTypeView].[LanguageCode],[ModuleTypeView].[AssemblyQualifiedName] -FROM dbo.fn_ModuleTypeView(@LanguageCode1, @LanguageCode2) AS ModuleTypeView +exec sp_executesql N'-- ModuleTypesForNotifications +SELECT [ModuleTypeView].[Id],[ModuleTypeView].[Name],[ModuleTypeView].[ManagementPackId],[ModuleTypeView].[Accessibility],[ModuleTypeView].[OutputMonitoringDataTypeId],[ModuleTypeView].[Role],[ModuleTypeView].[CanGuaranteeDelivery],[ModuleTypeView].[IncludeSchemaTypes],[ModuleTypeView].[IsPassThrough],[ModuleTypeView].[IsStateful],[ModuleTypeView].[IsTriggerOnly],[ModuleTypeView].[Batching],[ModuleTypeView].[ImplementationXml],[ModuleTypeView].[ConfigurationXsd],[ModuleTypeView].[InputMonitoringDataTypes],[ModuleTypeView].[RunAs],[ModuleTypeView].[TimeAdded],[ModuleTypeView].[LastModified],[ModuleTypeView].[HasUIPageSet],[ModuleTypeView].[DisplayName],[ModuleTypeView].[Description],[ModuleTypeView].[LanguageCode],[ModuleTypeView].[AssemblyQualifiedName] +FROM dbo.fn_ModuleTypeView(@LanguageCode1, @LanguageCode2) AS ModuleTypeView WHERE ((ModuleTypeView.Role = 3 AND ModuleTypeView.ManagementPackId = @ManagementPackId))',N'@LanguageCode1 varchar(3),@LanguageCode2 varchar(3),@ManagementPackId uniqueidentifier',@LanguageCode1='ENU',@LanguageCode2=NULL,@ManagementPackId='DCFDEDC4-68BD-42B4-1E9A-BA94B1577732' \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Notifications_Subscriptions.sql b/SQL Queries/OperationsManager/Notifications_Subscriptions.sql index 7703541..d11986e 100644 --- a/SQL Queries/OperationsManager/Notifications_Subscriptions.sql +++ b/SQL Queries/OperationsManager/Notifications_Subscriptions.sql @@ -1,37 +1,37 @@ --- This is the 2 queries joined together to provide the data that we want -Select Subscriptions.DisplayName, Subscriptions.RuleId, -Case subscriptions.enabled When 0 Then 'No' Else 'Yes' End as SubscriptionEnabled, -Subscribers.SubscriberName, Subscribers.DeviceName, Subscribers.DeviceProtocol, -Subscribers.DeviceAddress -FROM ( ---This is the whole subscriber query with Address -Select r.SubscriberName, r.SubscriberId, -D.C.value('Name[1]','varchar(4000)') DeviceName, -D.C.value('Protocol[1]','varchar(4000)') DeviceProtocol, -D.C.value('Address[1]','varchar(4000)') DeviceAddress -FROM (Select N.C.value('Name[1]','varchar(4000)') SubscriberName, - N.C.value('RecipientId[1]','varchar(4000)') SubscriberId, - n.c.query('.') as xmlquery -from (Select cast(MDTImplementationXML as xml) Recxml FROM [dbo].[ModuleType] mt -Where MDTName = 'Microsoft.SystemCenter.Notification.Recipients' )a Cross Apply Recxml.nodes('//Recipient') N(C)) r -Cross Apply xmlquery.nodes('//Device') D(C) -) Subscribers -Join -(--These are the subscriptions -Select r.RuleId, r.RuleModuleId, r.enabled, R.DisplayName, -D.C.value('RecipientId[1]','varchar(4000)') SubscriberId -FROM (Select RuleId, rm.RuleModuleId, enabled, r.DisplayName, - cast(RuleModuleConfiguration as XML) xmlquery - FROM - RuleModule rm - join RuleView r on rm.RuleId = r.Id - where r.Category = 'Notification' - and RuleModuleName = 'CD1' - --and Enabled <> 0 - ) r -Cross Apply xmlquery.nodes('//DirectoryReference') D(C) -) Subscriptions on Subscribers.SubscriberId = Subscriptions.SubscriberId ---Where ((Subscriptions.RuleId = Replace(Replace(@SubscriptionId,'{',''),'}','') - --or @SubscriptionId IS NULL) ---and DeviceProtocol in ('SMS','SMTP')) +-- This is the 2 queries joined together to provide the data that we want +Select Subscriptions.DisplayName, Subscriptions.RuleId, +Case subscriptions.enabled When 0 Then 'No' Else 'Yes' End as SubscriptionEnabled, +Subscribers.SubscriberName, Subscribers.DeviceName, Subscribers.DeviceProtocol, +Subscribers.DeviceAddress +FROM ( +--This is the whole subscriber query with Address +Select r.SubscriberName, r.SubscriberId, +D.C.value('Name[1]','varchar(4000)') DeviceName, +D.C.value('Protocol[1]','varchar(4000)') DeviceProtocol, +D.C.value('Address[1]','varchar(4000)') DeviceAddress +FROM (Select N.C.value('Name[1]','varchar(4000)') SubscriberName, + N.C.value('RecipientId[1]','varchar(4000)') SubscriberId, + n.c.query('.') as xmlquery +from (Select cast(MDTImplementationXML as xml) Recxml FROM [dbo].[ModuleType] mt +Where MDTName = 'Microsoft.SystemCenter.Notification.Recipients' )a Cross Apply Recxml.nodes('//Recipient') N(C)) r +Cross Apply xmlquery.nodes('//Device') D(C) +) Subscribers +Join +(--These are the subscriptions +Select r.RuleId, r.RuleModuleId, r.enabled, R.DisplayName, +D.C.value('RecipientId[1]','varchar(4000)') SubscriberId +FROM (Select RuleId, rm.RuleModuleId, enabled, r.DisplayName, + cast(RuleModuleConfiguration as XML) xmlquery + FROM + RuleModule rm + join RuleView r on rm.RuleId = r.Id + where r.Category = 'Notification' + and RuleModuleName = 'CD1' + --and Enabled <> 0 + ) r +Cross Apply xmlquery.nodes('//DirectoryReference') D(C) +) Subscriptions on Subscribers.SubscriberId = Subscriptions.SubscriberId +--Where ((Subscriptions.RuleId = Replace(Replace(@SubscriptionId,'{',''),'}','') + --or @SubscriptionId IS NULL) +--and DeviceProtocol in ('SMS','SMTP')) order by 1,2 \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Orphaned.sql b/SQL Queries/OperationsManager/Orphaned.sql index 3f989c5..41b2885 100644 --- a/SQL Queries/OperationsManager/Orphaned.sql +++ b/SQL Queries/OperationsManager/Orphaned.sql @@ -1,34 +1,34 @@ ---Detect Orphaned objects; Added FullName --- September 9th, 2022 - Updated to include HealthServiceWatchers -declare @DiscoverySourceId uniqueidentifier; -declare @TimeGenerated datetime; -set @TimeGenerated = GETUTCDATE(); -set @DiscoverySourceId = dbo.fn_DiscoverySourceId_User(); -SELECT TME.[TypedManagedEntityid], -BHS.DisplayName, -BHS.FullName -FROM MTV_HealthService HS -INNER JOIN dbo.[BaseManagedEntity] BHS -ON BHS.[BaseManagedEntityId] = HS.[BaseManagedEntityId] --- get host managed computer instances -INNER JOIN dbo.[TypedManagedEntity] TME -ON TME.[BaseManagedEntityId] = BHS.[TopLevelHostEntityId] -AND TME.[IsDeleted] = 0 -INNER JOIN dbo.[DerivedManagedTypes] DMT -ON DMT.[DerivedTypeId] = TME.[ManagedTypeId] -INNER JOIN dbo.[ManagedType] BT -ON DMT.[BaseTypeId] = BT.[ManagedTypeId] -AND BT.[TypeName] = N'Microsoft.Windows.Computer' --- only with missing primary -LEFT OUTER JOIN dbo.Relationship HSC -ON HSC.[SourceEntityId] = HS.[BaseManagedEntityId] -AND HSC.[RelationshipTypeId] = dbo.fn_RelationshipTypeId_HealthServiceCommunication() -AND HSC.[IsDeleted] = 0 --- Check Health Service Watcher -INNER JOIN MT_Microsoft$SystemCenter$HealthServiceWatcher HSW -ON BHS.BaseManagedEntityId = HSW.BaseManagedEntityId -INNER JOIN DiscoverySourceToTypedManagedEntity DSTME -ON DSTME.[TypedManagedEntityId] = TME.[TypedManagedEntityId] -AND DSTME.[DiscoverySourceId] = @DiscoverySourceId -WHERE HS.[IsAgent] = 1 -AND HSC.[RelationshipId] IS NULL +--Detect Orphaned objects; Added FullName +-- September 9th, 2022 - Updated to include HealthServiceWatchers +declare @DiscoverySourceId uniqueidentifier; +declare @TimeGenerated datetime; +set @TimeGenerated = GETUTCDATE(); +set @DiscoverySourceId = dbo.fn_DiscoverySourceId_User(); +SELECT TME.[TypedManagedEntityid], +BHS.DisplayName, +BHS.FullName +FROM MTV_HealthService HS +INNER JOIN dbo.[BaseManagedEntity] BHS +ON BHS.[BaseManagedEntityId] = HS.[BaseManagedEntityId] +-- get host managed computer instances +INNER JOIN dbo.[TypedManagedEntity] TME +ON TME.[BaseManagedEntityId] = BHS.[TopLevelHostEntityId] +AND TME.[IsDeleted] = 0 +INNER JOIN dbo.[DerivedManagedTypes] DMT +ON DMT.[DerivedTypeId] = TME.[ManagedTypeId] +INNER JOIN dbo.[ManagedType] BT +ON DMT.[BaseTypeId] = BT.[ManagedTypeId] +AND BT.[TypeName] = N'Microsoft.Windows.Computer' +-- only with missing primary +LEFT OUTER JOIN dbo.Relationship HSC +ON HSC.[SourceEntityId] = HS.[BaseManagedEntityId] +AND HSC.[RelationshipTypeId] = dbo.fn_RelationshipTypeId_HealthServiceCommunication() +AND HSC.[IsDeleted] = 0 +-- Check Health Service Watcher +INNER JOIN MT_Microsoft$SystemCenter$HealthServiceWatcher HSW +ON BHS.BaseManagedEntityId = HSW.BaseManagedEntityId +INNER JOIN DiscoverySourceToTypedManagedEntity DSTME +ON DSTME.[TypedManagedEntityId] = TME.[TypedManagedEntityId] +AND DSTME.[DiscoverySourceId] = @DiscoverySourceId +WHERE HS.[IsAgent] = 1 +AND HSC.[RelationshipId] IS NULL \ No newline at end of file diff --git a/SQL Queries/OperationsManager/PartitionAndGroom_Retention.sql b/SQL Queries/OperationsManager/PartitionAndGroom_Retention.sql index 4a2a2e5..ea984ba 100644 --- a/SQL Queries/OperationsManager/PartitionAndGroom_Retention.sql +++ b/SQL Queries/OperationsManager/PartitionAndGroom_Retention.sql @@ -1,10 +1,10 @@ -SELECT [ObjectName] - ,[IsPartitioned] - ,[InsertViewName] - ,[GroomingSproc] - ,[DaysToKeep] - ,[GroomingRunTime] - ,[DataGroomedMaxTime] - ,[IsInternal] - FROM [PartitionAndGroomingSettings] WITH (NOLOCK) - ORDER BY ObjectName +SELECT [ObjectName] + ,[IsPartitioned] + ,[InsertViewName] + ,[GroomingSproc] + ,[DaysToKeep] + ,[GroomingRunTime] + ,[DataGroomedMaxTime] + ,[IsInternal] + FROM [PartitionAndGroomingSettings] WITH (NOLOCK) + ORDER BY ObjectName \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Perf_byCounter.sql b/SQL Queries/OperationsManager/Perf_ByCounter.sql similarity index 56% rename from SQL Queries/OperationsManager/Perf_byCounter.sql rename to SQL Queries/OperationsManager/Perf_ByCounter.sql index 6168186..a4c57a9 100644 --- a/SQL Queries/OperationsManager/Perf_byCounter.sql +++ b/SQL Queries/OperationsManager/Perf_ByCounter.sql @@ -1,9 +1,10 @@ -/*Top 30 performance insertions by perf object and counter name: */ -SELECT TOP (30) pcv.ObjectName, r.DisplayName AS 'RuleName', pcv.CounterName, MPV.DisplayName AS 'MPDisplayName', pcv.RuleId, COUNT(pcv.CounterName) AS Total +/*Top 100 performance insertions by perf object and counter name: */ +SELECT TOP (100) pcv.ObjectName, r.DisplayName AS 'RuleName', pcv.CounterName, MPV.DisplayName AS 'MPDisplayName', pcv.RuleId, MPV.LanguageCode, COUNT(pcv.CounterName) AS Total FROM PerformanceDataAllView AS pdv INNER JOIN PerformanceCounterView AS pcv ON pdv.PerformanceSourceInternalId = pcv.PerformanceSourceInternalId INNER JOIN RuleView AS r ON pcv.RuleId = r.Id INNER JOIN ManagementPackView AS MPV ON r.ManagementPackId = MPV.Id -GROUP BY pcv.ObjectName, pcv.CounterName, MPV.DisplayName, pcv.RuleId, r.DisplayName +WHERE MPV.LanguageCode = 'ENU' +GROUP BY pcv.ObjectName, pcv.CounterName, MPV.DisplayName, pcv.RuleId, r.DisplayName, MPV.LanguageCode ORDER BY Total DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Recently_Changed_Disc_OpsDB.sql b/SQL Queries/OperationsManager/Recently_Changed_Disc_OpsDB.sql index efd7a45..fdcbcae 100644 --- a/SQL Queries/OperationsManager/Recently_Changed_Disc_OpsDB.sql +++ b/SQL Queries/OperationsManager/Recently_Changed_Disc_OpsDB.sql @@ -1,14 +1,14 @@ --- Gather all Discoveries Modified in the last 180 days. -SELECT DiscoveryName, - mp.MPFriendlyName, - REPLACE(REPLACE(REPLACE(DiscoveryEnabled, '4', 'True'),'0', 'False'), '3', 'onEssentialMonitoring') as 'DiscoveryEnabled', - CASE WHEN bme.DisplayName IS NULL then mt.TypeName else bme.DisplayName END as 'DiscoveryTarget', - d.LastModified, - d.TimeAdded -FROM Discovery d WITH (NOLOCK) LEFT JOIN -BaseManagedEntity AS bme WITH (NOLOCK) ON d.DiscoveryTarget = bme.BaseManagedEntityId INNER JOIN -ManagedType AS mt WITH (NOLOCK) ON d.DiscoveryTarget = mt.ManagedTypeId INNER JOIN -ManagementPack mp WITH (NOLOCK) -ON d.ManagementPackId = mp.ManagementPackId -WHERE d.LastModified > DATEADD(day, -180, GETUTCDATE()) +-- Gather all Discoveries Modified in the last 180 days. +SELECT DiscoveryName, + mp.MPFriendlyName, + REPLACE(REPLACE(REPLACE(DiscoveryEnabled, '4', 'True'),'0', 'False'), '3', 'onEssentialMonitoring') as 'DiscoveryEnabled', + CASE WHEN bme.DisplayName IS NULL then mt.TypeName else bme.DisplayName END as 'DiscoveryTarget', + d.LastModified, + d.TimeAdded +FROM Discovery d WITH (NOLOCK) LEFT JOIN +BaseManagedEntity AS bme WITH (NOLOCK) ON d.DiscoveryTarget = bme.BaseManagedEntityId INNER JOIN +ManagedType AS mt WITH (NOLOCK) ON d.DiscoveryTarget = mt.ManagedTypeId INNER JOIN +ManagementPack mp WITH (NOLOCK) +ON d.ManagementPackId = mp.ManagementPackId +WHERE d.LastModified > DATEADD(day, -180, GETUTCDATE()) ORDER BY d.LastModified DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Relationships.sql b/SQL Queries/OperationsManager/Relationships.sql index e7c99ca..893acad 100644 --- a/SQL Queries/OperationsManager/Relationships.sql +++ b/SQL Queries/OperationsManager/Relationships.sql @@ -1,4 +1,4 @@ -SELECT COUNT(*) AS 'ContainedMembers', SourceObjectDisplayName, SourceObjectFullName -FROM RelationshipGenericView -GROUP BY SourceObjectDisplayName,SourceObjectFullName +SELECT COUNT(*) AS 'ContainedMembers', SourceObjectDisplayName, SourceObjectFullName +FROM RelationshipGenericView +GROUP BY SourceObjectDisplayName,SourceObjectFullName ORDER BY COUNT(*) DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/ResourcePools.sql b/SQL Queries/OperationsManager/ResourcePools.sql index 70a4c4b..26a477c 100644 --- a/SQL Queries/OperationsManager/ResourcePools.sql +++ b/SQL Queries/OperationsManager/ResourcePools.sql @@ -1,4 +1,4 @@ --- Modified by Alex Kremenetskiy +-- Modified by Alex Kremenetskiy SET NOCOUNT ON DECLARE @Statement nvarchar(max) @@ -62,4 +62,4 @@ set @Statement = ' ORDER BY ResourcePool, Member' Print @Statement Exec (@Statement) - DROP TABLE #IsDynamic + DROP TABLE #IsDynamic \ No newline at end of file diff --git a/SQL Queries/OperationsManager/Resource_Pool_OpsDB.sql b/SQL Queries/OperationsManager/Resource_Pool_OpsDB.sql deleted file mode 100644 index a9a50d6..0000000 --- a/SQL Queries/OperationsManager/Resource_Pool_OpsDB.sql +++ /dev/null @@ -1,34 +0,0 @@ -SET NOCOUNT ON -DECLARE -@Statement nvarchar(max) -,@MicrosoftSystemCenterManagementService nvarchar(255) -,@ManagementService_HealthServiceId nvarchar(255) -,@BaseManagedEntityDisplayName nvarchar(255) -SELECT @MicrosoftSystemCenterManagementService = ManagedTypeViewName -FROM dbo.ManagedType WITH (NOLOCK) -WHERE (ManagedTypeId = dbo.fn_ManagedTypeId_MicrosoftSystemCenterManagementService()) -PRINT @MicrosoftSystemCenterManagementService -SELECT @ManagementService_HealthServiceId = ColumnName -FROM dbo.ManagedTypeProperty WITH (NOLOCK) -WHERE (ManagedTypeId = dbo.fn_ManagedTypeId_MicrosoftSystemCenterManagementService()) -AND (ManagedTypePropertyId = dbo.fn_ManagedTypePropertyId_MicrosoftSystemCenterManagementService_HealthServiceId()) -PRINT @ManagementService_HealthServiceId -SELECT @BaseManagedEntityDisplayName = S.COLUMN_NAME -FROM INFORMATION_SCHEMA.COLUMNS AS S WITH (NOLOCK) -WHERE S.TABLE_NAME COLLATE DATABASE_DEFAULT IN -(SELECT ManagedTypeViewName AS [TABLE_NAME] FROM dbo.ManagedType) -AND S.TABLE_NAME = @MicrosoftSystemCenterManagementService -AND S.COLUMN_NAME like 'DisplayName%' -PRINT @BaseManagedEntityDisplayName -set @Statement = ' -SELECT -BME.DisplayName AS ResourcePool -,[MS].' + QUOTENAME(@BaseManagedEntityDisplayName) + ' AS Member -FROM dbo.Relationship R -JOIN ' + QUOTENAME(@MicrosoftSystemCenterManagementService) + ' MS ON (R.TargetEntityId = MS.BaseManagedEntityId) -JOIN BaseManagedEntity BME ON BME.BaseManagedEntityId = R.SourceEntityId -WHERE (RelationshipTypeId = dbo.fn_ManagedTypeId_MicrosoftSystemCenterManagementServicePoolContainsManagementService()) -AND (R.IsDeleted = 0) AND (BME.IsDeleted = 0) -Order By ResourcePool ASC, Member ASC' ---Print @Statement -Exec (@Statement) diff --git a/SQL Queries/OperationsManager/RunAsAccounts_OpsDB.sql b/SQL Queries/OperationsManager/RunAsAccounts_OpsDB.sql index 6b26d93..457a2d6 100644 --- a/SQL Queries/OperationsManager/RunAsAccounts_OpsDB.sql +++ b/SQL Queries/OperationsManager/RunAsAccounts_OpsDB.sql @@ -1,14 +1,14 @@ -exec sp_executesql N'-- CredentialManagerStoreByCriteriaWithoutSecretData -SELECT -Case [SecureData].[Type] -When 0 then ''SNMPv3 Account'' -When 1 then ''Action Account'' -When 2 then ''Windows'' -When 3 then ''Simple Authentication'' -When 4 then ''Basic Authentication'' -When 5 then ''Digest Authentication'' -When 6 then ''Community String'' -When 7 then ''Binary Authentication'' -End as [Type],[SecureData].[Name],[SecureData].[Description],[SecureData].[Domain],[SecureData].[UserName],[SecureData].[LastModified],REPLACE(REPLACE([SecureData].[IsSystem],0,''False''),1,''True'') AS IsSystem,[SecureData].[AssemblyQualifiedName],[SecureData].[Id],[SecureData].[SecureStorageId],[SecureData].[ConfigurationXml] -FROM dbo.fn_CredentialManagerStoreByCriteriaWithoutSecretDataView(@LanguageCode1, @LanguageCode2) AS SecureData +exec sp_executesql N'-- CredentialManagerStoreByCriteriaWithoutSecretData +SELECT +Case [SecureData].[Type] +When 0 then ''SNMPv3 Account'' +When 1 then ''Action Account'' +When 2 then ''Windows'' +When 3 then ''Simple Authentication'' +When 4 then ''Basic Authentication'' +When 5 then ''Digest Authentication'' +When 6 then ''Community String'' +When 7 then ''Binary Authentication'' +End as [Type],[SecureData].[Name],[SecureData].[Description],[SecureData].[Domain],[SecureData].[UserName],[SecureData].[LastModified],REPLACE(REPLACE([SecureData].[IsSystem],0,''False''),1,''True'') AS IsSystem,[SecureData].[AssemblyQualifiedName],[SecureData].[Id],[SecureData].[SecureStorageId],[SecureData].[ConfigurationXml] +FROM dbo.fn_CredentialManagerStoreByCriteriaWithoutSecretDataView(@LanguageCode1, @LanguageCode2) AS SecureData ORDER BY Type, Name',N'@LanguageCode1 nvarchar(3),@LanguageCode2 nvarchar(3)',@LanguageCode1=N'ENU',@LanguageCode2=N'ENU' \ No newline at end of file diff --git a/SQL Queries/OperationsManager/RunAsProfiles.sql b/SQL Queries/OperationsManager/RunAsProfiles.sql index 23c5b8c..5bb3dd7 100644 --- a/SQL Queries/OperationsManager/RunAsProfiles.sql +++ b/SQL Queries/OperationsManager/RunAsProfiles.sql @@ -1,21 +1,21 @@ ---get all Run As profiles and associated accounts, - --credentials, Secure Storage ID values and targets -SELECT [Profile].SecureReferenceName ProfileName - , Account.Name AccountName - , Account.Domain - , Account.UserName - , Account.LastModified - , [Override].OverrideName - , [Override].Value SSID - , bme.FullName - , mt.TypeName -FROM CredentialManagerSecureStorage AS Account WITH (NOLOCK) -JOIN SecureReferenceOverride AS [Override] WITH (NOLOCK) -ON CONVERT (varchar(80), Account.SecureStorageId, 2) = [Override].Value -JOIN SecureReference AS [Profile] WITH (NOLOCK) -ON [Override].SecureReferenceId = [Profile].SecureReferenceId -JOIN ManagedType mt WITH (NOLOCK) -ON [Override].TypeContext = mt.ManagedTypeId -LEFT JOIN BaseManagedEntity bme WITH (NOLOCK) -ON [Override].InstanceContext = bme.BaseManagedEntityId +--get all Run As profiles and associated accounts, + --credentials, Secure Storage ID values and targets +SELECT [Profile].SecureReferenceName ProfileName + , Account.Name AccountName + , Account.Domain + , Account.UserName + , Account.LastModified + , [Override].OverrideName + , [Override].Value SSID + , bme.FullName + , mt.TypeName +FROM CredentialManagerSecureStorage AS Account WITH (NOLOCK) +JOIN SecureReferenceOverride AS [Override] WITH (NOLOCK) +ON CONVERT (varchar(80), Account.SecureStorageId, 2) = [Override].Value +JOIN SecureReference AS [Profile] WITH (NOLOCK) +ON [Override].SecureReferenceId = [Profile].SecureReferenceId +JOIN ManagedType mt WITH (NOLOCK) +ON [Override].TypeContext = mt.ManagedTypeId +LEFT JOIN BaseManagedEntity bme WITH (NOLOCK) +ON [Override].InstanceContext = bme.BaseManagedEntityId ORDER BY ProfileName \ No newline at end of file diff --git a/SQL Queries/OperationsManager/SQL_DBOwner_OpsDB.sql b/SQL Queries/OperationsManager/SQL_DBOwner_OpsDB.sql index 60a78a2..194c571 100644 --- a/SQL Queries/OperationsManager/SQL_DBOwner_OpsDB.sql +++ b/SQL Queries/OperationsManager/SQL_DBOwner_OpsDB.sql @@ -1,4 +1,4 @@ -select DB_NAME(DB_ID()), suser_sname(owner_sid) AS 'Owner' -from sys.databases sdb -WHERE database_id = DB_ID() -go +-- Get current context DB Owner +select DB_NAME(DB_ID()), suser_sname(owner_sid) AS 'Owner' +from sys.databases sdb +WHERE database_id = DB_ID() \ No newline at end of file diff --git a/SQL Queries/OperationsManager/SQL_DBSize_OpsDB.sql b/SQL Queries/OperationsManager/SQL_DBSize_OpsDB.sql index 0a4a493..b582ff6 100644 --- a/SQL Queries/OperationsManager/SQL_DBSize_OpsDB.sql +++ b/SQL Queries/OperationsManager/SQL_DBSize_OpsDB.sql @@ -25,4 +25,4 @@ sf.FILENAME AS 'Location', sf.FILEID AS 'FileId' FROM dbo.sysfiles sf WITH (NOLOCK) JOIN sys.master_files smf WITH (NOLOCK) ON smf.physical_name = sf.filename -ORDER BY FileId +ORDER BY FileId \ No newline at end of file diff --git a/SQL Queries/OperationsManager/SQL_DBSize_OpsDB_TempDB.sql b/SQL Queries/OperationsManager/SQL_DBSize_OpsDB_TempDB.sql new file mode 100644 index 0000000..4d93249 --- /dev/null +++ b/SQL Queries/OperationsManager/SQL_DBSize_OpsDB_TempDB.sql @@ -0,0 +1,30 @@ +-- Modified 2/9/2022 - Included Free Space %, added MB to value fields. +-- Modified 6/21/2022 - Attempted to fix Arithmetic Overflow error when run in large environments. Added 'SpaceUsed(%)' and 'AutoGrowthStatus' columns. +-- Blake Drumm (blakedrumm@microsoft.com) +USE tempdb + +SELECT sf.NAME AS 'Name', +CONCAT(convert(decimal(12,2), round(sf.size/128.000, 2)), ' MB') AS 'FileSize(MB)', +CONCAT(convert(int, round(100 * convert(bigint,(sf.size-fileproperty(sf.name, 'SpaceUsed'))) / convert(bigint,sf.size), 2)),' %') AS 'FreeSpace(%)', +CONCAT(convert(decimal(12,2), round((sf.size-fileproperty(sf.name, 'SpaceUsed'))/128.000, 2)), ' MB') AS 'FreeSpace(MB)', +CONCAT(convert(int, 100 - (round(100 * convert(bigint,(sf.size-fileproperty(sf.name, 'SpaceUsed'))) / convert(bigint,sf.size), 2))),' %') AS 'SpaceUsed(%)', +CONCAT(convert(decimal(12,2), round(fileproperty(sf.name, 'SpaceUsed')/128.000, 2)), ' MB') AS 'SpaceUsed(MB)', +CASE smf.growth + WHEN 0 THEN 'Disabled' + ELSE 'Enabled' +END AS 'AutoGrowthStatus', +CASE smf.is_percent_growth + WHEN 1 THEN CONCAT(CONVERT(bigint, smf.growth), ' %') + ELSE CONCAT(convert(decimal(12,2), smf.growth/128),' MB') +END AS 'AutoGrowth', +CASE (sf.maxsize) + WHEN -1 THEN 'Unlimited' + WHEN 268435456 THEN 'Max Size (2TB)' + ELSE CONCAT(convert(decimal(12,2), round(sf.maxsize/128.000, 2)), ' MB') +END AS 'AutoGrowthMB(MAX)', +sf.status, +sf.FILENAME AS 'Location', +sf.FILEID AS 'FileId' +FROM dbo.sysfiles sf WITH (NOLOCK) +JOIN sys.master_files smf WITH (NOLOCK) ON smf.physical_name = sf.filename +ORDER BY FileId \ No newline at end of file diff --git a/SQL Queries/OperationsManager/SQL_ErrorLogLocation_OpsDB.sql b/SQL Queries/OperationsManager/SQL_ErrorLogLocation_OpsDB.sql index eb1b5c3..5af4a0e 100644 --- a/SQL Queries/OperationsManager/SQL_ErrorLogLocation_OpsDB.sql +++ b/SQL Queries/OperationsManager/SQL_ErrorLogLocation_OpsDB.sql @@ -1 +1 @@ -xp_readerrorlog 0, 1, N'Logging SQL Server messages in file' +xp_readerrorlog 0, 1, N'Logging SQL Server messages in file' diff --git a/SQL Queries/OperationsManager/SQL_Primary_Replicas_OpsMgr.sql b/SQL Queries/OperationsManager/SQL_Primary_Replicas_OpsMgr.sql index 5099976..115dbf1 100644 --- a/SQL Queries/OperationsManager/SQL_Primary_Replicas_OpsMgr.sql +++ b/SQL Queries/OperationsManager/SQL_Primary_Replicas_OpsMgr.sql @@ -1,19 +1,19 @@ -IF SERVERPROPERTY ('IsHadrEnabled') = 1 -BEGIN -SELECT - AGC.name -- Availability Group - , RCS.replica_server_name -- SQL cluster node name - , ARS.role_desc -- Replica Role - , AGL.dns_name -- Listener Name -FROM - sys.availability_groups_cluster AS AGC - INNER JOIN sys.dm_hadr_availability_replica_cluster_states AS RCS - ON - RCS.group_id = AGC.group_id - INNER JOIN sys.dm_hadr_availability_replica_states AS ARS - ON - ARS.replica_id = RCS.replica_id - INNER JOIN sys.availability_group_listeners AS AGL - ON - AGL.group_id = ARS.group_id +IF SERVERPROPERTY ('IsHadrEnabled') = 1 +BEGIN +SELECT + AGC.name -- Availability Group + , RCS.replica_server_name -- SQL cluster node name + , ARS.role_desc -- Replica Role + , AGL.dns_name -- Listener Name +FROM + sys.availability_groups_cluster AS AGC + INNER JOIN sys.dm_hadr_availability_replica_cluster_states AS RCS + ON + RCS.group_id = AGC.group_id + INNER JOIN sys.dm_hadr_availability_replica_states AS ARS + ON + ARS.replica_id = RCS.replica_id + INNER JOIN sys.availability_group_listeners AS AGL + ON + AGL.group_id = ARS.group_id END \ No newline at end of file diff --git a/SQL Queries/OperationsManager/SQL_Properties_OpsDB.sql b/SQL Queries/OperationsManager/SQL_Properties_OpsDB.sql index 9349460..d11467a 100644 --- a/SQL Queries/OperationsManager/SQL_Properties_OpsDB.sql +++ b/SQL Queries/OperationsManager/SQL_Properties_OpsDB.sql @@ -1,4 +1,4 @@ -SELECT CASE +SELECT CASE (SELECT is_broker_enabled FROM sys.databases WHERE name=db_name()) @@ -49,4 +49,4 @@ SELECT CASE END AS [IsFullTextInstalled], CONVERT(nvarchar(50), serverproperty('Collation')) AS COLLATION, CONVERT(nvarchar(50), serverproperty('ComputerNamePhysicalNetBIOS')) AS ComputerNamePhysicalNetBIOS, - CONVERT(nvarchar(50), serverproperty('ComputerNamePhysicalNetBIOS')) AS 'SqlHost' + CONVERT(nvarchar(50), serverproperty('ComputerNamePhysicalNetBIOS')) AS 'SqlHost' \ No newline at end of file diff --git a/SQL Queries/OperationsManager/SQL_UserMapping_OpsDB.sql b/SQL Queries/OperationsManager/SQL_UserMapping_OpsDB.sql index 9c2a9d4..ace6696 100644 --- a/SQL Queries/OperationsManager/SQL_UserMapping_OpsDB.sql +++ b/SQL Queries/OperationsManager/SQL_UserMapping_OpsDB.sql @@ -1,32 +1,32 @@ -DECLARE @DB_Users TABLE -(DBName sysname, UserName sysname, LoginType sysname, AssociatedRole varchar(max),create_date datetime,modify_date datetime) - -INSERT @DB_Users -EXEC sp_MSforeachdb - -' -use [?] -SELECT ''?'' AS DB_Name, -case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName, -prin.type_desc AS LoginType, -isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole ,create_date,modify_date -FROM sys.database_principals prin -LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id -WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and -prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%''' - -SELECT -dbname,username ,logintype ,create_date ,modify_date , -STUFF( -( -SELECT ',' + CONVERT(VARCHAR(500),associatedrole) -FROM @DB_Users user2 -WHERE -user1.DBName=user2.DBName AND user1.UserName=user2.UserName -FOR XML PATH('') -) -,1,1,'') AS Permissions_user -FROM @DB_Users user1 -GROUP BY -dbname,username ,logintype ,create_date ,modify_date -ORDER BY DBName, username +DECLARE @DB_Users TABLE +(DBName sysname, UserName sysname, LoginType sysname, AssociatedRole varchar(max),create_date datetime,modify_date datetime) + +INSERT @DB_Users +EXEC sp_MSforeachdb + +' +use [?] +SELECT ''?'' AS DB_Name, +case prin.name when ''dbo'' then prin.name + '' (''+ (select SUSER_SNAME(owner_sid) from master.sys.databases where name =''?'') + '')'' else prin.name end AS UserName, +prin.type_desc AS LoginType, +isnull(USER_NAME(mem.role_principal_id),'''') AS AssociatedRole ,create_date,modify_date +FROM sys.database_principals prin +LEFT OUTER JOIN sys.database_role_members mem ON prin.principal_id=mem.member_principal_id +WHERE prin.sid IS NOT NULL and prin.sid NOT IN (0x00) and +prin.is_fixed_role <> 1 AND prin.name NOT LIKE ''##%''' + +SELECT +dbname,username ,logintype ,create_date ,modify_date , +STUFF( +( +SELECT ',' + CONVERT(VARCHAR(500),associatedrole) +FROM @DB_Users user2 +WHERE +user1.DBName=user2.DBName AND user1.UserName=user2.UserName +FOR XML PATH('') +) +,1,1,'') AS Permissions_user +FROM @DB_Users user1 +GROUP BY +dbname,username ,logintype ,create_date ,modify_date +ORDER BY DBName, username \ No newline at end of file diff --git a/SQL Queries/OperationsManager/State_UnhealthyMonitors.sql b/SQL Queries/OperationsManager/State_UnhealthyMonitors.sql index 8d25329..eeb4077 100644 --- a/SQL Queries/OperationsManager/State_UnhealthyMonitors.sql +++ b/SQL Queries/OperationsManager/State_UnhealthyMonitors.sql @@ -1,14 +1,14 @@ -SELECT - count(*) as 'UnhealthyMonitorInstances', -mv.DisplayName AS 'MonitorDisplayName', -mv.Name AS 'MonitorName', -MonitorState = CASE - WHEN s.HealthState = 3 THEN 'Critical' - WHEN s.HealthState = 2 THEN 'Warning' - END -FROM State s -JOIN MonitorView mv ON mv.Id = s.MonitorId -WHERE s.HealthState IN (2,3) -AND mv.IsUnitMonitor = 1 -GROUP BY mv.Name,mv.DisplayName,s.HealthState +SELECT + count(*) as 'UnhealthyMonitorInstances', +mv.DisplayName AS 'MonitorDisplayName', +mv.Name AS 'MonitorName', +MonitorState = CASE + WHEN s.HealthState = 3 THEN 'Critical' + WHEN s.HealthState = 2 THEN 'Warning' + END +FROM State s +JOIN MonitorView mv ON mv.Id = s.MonitorId +WHERE s.HealthState IN (2,3) +AND mv.IsUnitMonitor = 1 +GROUP BY mv.Name,mv.DisplayName,s.HealthState ORDER by count(*) DESC \ No newline at end of file diff --git a/SQL Queries/OperationsManager/TaskStatus.sql b/SQL Queries/OperationsManager/TaskStatus.sql index 08582e3..c5350a5 100644 --- a/SQL Queries/OperationsManager/TaskStatus.sql +++ b/SQL Queries/OperationsManager/TaskStatus.sql @@ -1,24 +1,24 @@ -/* Gather the Task(s) Status from OperationsManager Database */ -SELECT [Id] - ,[TaskId] - ,[BatchId] - ,[SubmittedBy] - ,[RunningAs] - ,[TargetObjectId] - ,[TargetClassId] - ,[LocationId] - ,[Status] - ,[StatusLastModified] - ,CAST([Output] as XML) as Output - ,[ErrorCode] - ,[ErrorMessage] - ,[TimeScheduled] - ,[TimeStarted] - ,[TimeFinished] - ,[ProgressValue] - ,[ProgressMessage] - ,[ProgressData] - ,[ProgressLastModified] - ,[LastModified] - ,[LastModifiedTimestamp] - FROM [dbo].[JobStatusView] +/* Gather the Task(s) Status from OperationsManager Database */ +SELECT [Id] + ,[TaskId] + ,[BatchId] + ,[SubmittedBy] + ,[RunningAs] + ,[TargetObjectId] + ,[TargetClassId] + ,[LocationId] + ,[Status] + ,[StatusLastModified] + ,CAST([Output] as XML) as Output + ,[ErrorCode] + ,[ErrorMessage] + ,[TimeScheduled] + ,[TimeStarted] + ,[TimeFinished] + ,[ProgressValue] + ,[ProgressMessage] + ,[ProgressData] + ,[ProgressLastModified] + ,[LastModified] + ,[LastModifiedTimestamp] + FROM [dbo].[JobStatusView] \ No newline at end of file diff --git a/SQL Queries/OperationsManager/UNIX_Agents.sql b/SQL Queries/OperationsManager/UNIX_Agents.sql index def1a7d..f405240 100644 --- a/SQL Queries/OperationsManager/UNIX_Agents.sql +++ b/SQL Queries/OperationsManager/UNIX_Agents.sql @@ -28,4 +28,4 @@ WHERE BaseTypeId = (select managedtypeid from managedtype where typename = ''Microsoft.Unix.Computer'') and DerivedIsAbstract = 0) ORDER BY DisplayName DESC' -exec(@query) +exec(@query) \ No newline at end of file diff --git a/SQL Queries/OperationsManager/UserRoles.sql b/SQL Queries/OperationsManager/UserRoles.sql index a9d8996..2c26c66 100644 --- a/SQL Queries/OperationsManager/UserRoles.sql +++ b/SQL Queries/OperationsManager/UserRoles.sql @@ -1,5 +1,5 @@ -SELECT - UserRoleName, - IsSystem -from +SELECT + UserRoleName, + IsSystem +from userrole WITH (NOLOCK) \ No newline at end of file