我们希望获得SQL Server实例级别(包括所有数据库)的每种对象类型的总数。
E.g。
Stored Procedures
Views
Tables
Constraints
Jobs
Linked Servers
Replication
此代码返回数据库级别的计数;如何更改此代码以显示实例级别的计数?
WITH objs AS
(
SELECT
type_desc AS Object_Type,
COUNT(*) AS Object_Count, 1 AS JoinColumn
FROM
sys.objects
--exclude internal tables, service queues, and system tables
WHERE
TYPE NOT IN ('IT', 'S', 'SQ')
GROUP BY
type_desc
),
tots AS
(
SELECT COUNT(*) AS Type_Count, 1 AS JoinColumn
FROM sys.objects
WHERE TYPE NOT IN ('IT', 'S', 'SQ')
)
SELECT
Object_Type, Object_Count, Type_Count,
CAST((Object_Count * 1.0) / Type_Count * 100 AS INT) AS Type_Pct
FROM objs o
JOIN tots s ON o.JoinColumn = s.JoinColumn
ORDER BY Object_Type;
此致
答案 0 :(得分:0)
以下是使用动态SQL和游标迭代服务器上所有用户数据库的示例。
SET NOCOUNT ON;
DECLARE @DatabaseCounts TABLE(
Object_Type nvarchar(60)
, Object_Count INT
);
DECLARE
@DatabaseName sysname
, @SQL nvarchar(MAX);
DECLARE Databases CURSOR LOCAL FAST_FORWARD FOR
SELECT name
FROM sys.databases
WHERE
name NOT IN(N'master',N'model',N'tempdb',N'msdb',N'SSISDB',N'distribution');
OPEN Databases;
WHILE 1 = 1
BEGIN
FETCH NEXT FROM Databases INTO @DatabaseName;
IF @@FETCH_STATUS = -1 BREAK;
SET @SQL = N'
USE ' + QUOTENAME(@DatabaseName) + N';
SELECT
type_desc AS Object_Type
, COUNT(*) AS Object_Count
FROM sys.objects
--exclude internal tables, service queues, and system tables
WHERE TYPE NOT IN (''IT'', ''S'', ''SQ'')
GROUP BY type_desc
';
INSERT INTO @DatabaseCounts
EXEC sp_executesql @SQL;
END;
CLOSE Databases;
DEALLOCATE Databases;
WITH
instance_counts1 AS (
SELECT
Object_Type
, SUM(Object_Count) AS Object_Count
FROM @DatabaseCounts
GROUP BY Object_Type
)
, instance_counts2 AS (
SELECT
Object_Type
, Object_Count
, (SELECT SUM(Object_Count) FROM instance_counts1) AS Type_Count
FROM instance_counts1
)
SELECT
Object_Type
, Object_Count
, Type_Count
, CAST(ROUND(Object_Count * 100.0 / Type_Count, 0) AS INT) AS Type_Pct
FROM instance_counts2;