這是一個非常更囉嗦的方法,但我認爲它給你你正在尋找什麼?
在數據庫中運行以下查詢要報告:
--Make a list of tables to target
DECLARE @HitList TABLE (
Id INT IDENTITY(1,1),
TableName VARCHAR(1024),
SchemaName VARCHAR(1024),
ColumnName VARCHAR(1024));
INSERT INTO
@HitList
SELECT
t.name,
s.name,
c.name
FROM
sys.columns c
INNER JOIN sys.tables t ON t.object_id = c.object_id
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE
c.system_type_id = 61; --DATETIME
--Now get the count of rows per year for each table in the list
DECLARE @Id INT = 1;
DECLARE @Count INT;
SELECT @Count = COUNT(*) FROM @HitList;
CREATE TABLE #Results (
Id INT,
[Year] INT,
[RowCount] INT);
WHILE @Id <= @Count
BEGIN
DECLARE @SQL NVARCHAR(MAX);
SELECT
@SQL = 'INSERT INTO #Results SELECT ' + CONVERT(VARCHAR(50), @Id) + ', YEAR([' + h.ColumnName + ']), COUNT(*) FROM [' + h.SchemaName + '].[' + h.TableName + '] GROUP BY YEAR([' + h.ColumnName + ']) ORDER BY 1;'
FROM
@HitList h
WHERE
Id = @Id;
EXEC(@SQL);
SELECT @Id = @Id + 1;
END;
--Output the results
SELECT
h.TableName + '.' + h.SchemaName + '.' + h.ColumnName AS [Table],
r.[Year],
r.[RowCount]
FROM
@HitList h
INNER JOIN #Results r ON r.Id = h.Id
ORDER BY
h.TableName,
h.ColumnName,
r.[Year];
例如,我跑這對我的一個SQL Server 2008和數據庫來獲得這些(部分)結果:
Table Year RowCount
ElecConsumptionForecast.Staging.LastReadingDate 2008 1680
ElecConsumptionForecast.Staging.LastReadingDate 2009 7978
ElecConsumptionForecast.Staging.LastReadingDate 2010 15398
ElecConsumptionForecast.Staging.LastReadingDate 2011 28769
ElecConsumptionForecast.Staging.LastReadingDate 2012 35682
ElecConsumptionForecast.Staging.LastReadingDate 2013 59047
ElecConsumptionForecast.Staging.LastReadingDate 2014 127668
您可以使用信息模式視圖來獲取所有日期列,並使用它來編寫動態SQL查詢。 –
到目前爲止,我已經有了一個腳本,它將向我提供數據庫中的所有表格,並且每個表格中的行數都是一樣的。 我正在使用SQL Server 2008. – user3712641