我需要从数据库中获取年度明智的表总行数。例如,如果我有一个数据库'Adventures2008',它有100个表。其中只有少数几个表有一个'[ModifiedTimeStamp]'列。现在我想以下面的格式获取数据集
少数几个表中没有“[ModifiedTimeStamp]”列。所以我需要一个SQL查询来获取所需的输出。我已经尝试了很多方法,但我无法使用'ModifiedTimeStamp'列循环表。
有人可以帮我吗?
如有任何疑问/问题,请与我们联系。
答案 0 :(得分:1)
如果我没错,
您需要的是每个包含列" ModifiedTimeStamp"的每个表的行数。正确?
尝试此查询...
-------------- find out tables containing column "MODIFIEDTIMESTAMP"-------------------
DROP TABLE #TMP1
SELECT
ROW_NUMBER() OVER(ORDER BY TABLE_NAME) ID,
TABLE_NAME
INTO
#TMP1
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
COLUMN_NAME LIKE '%MODIFIEDTIMESTAMP%'
ORDER BY TABLE_NAME
-----------------------------------------------------------------------------
------------------loop each tables found, -------------------------------------
DECLARE @CNT INT = 1 ;
DECLARE @RN INT = (SELECT COUNT(1) FROM #TMP1)
IF @RN >1
BEGIN
DECLARE @SQL NVARCHAR(MAX)='
IF OBJECT_ID(''TEMPDB.DBO.##TMP2'', ''U'') IS NOT NULL DROP TABLE ##TMP2
SELECT * INTO ##TMP2 FROM ('
WHILE @CNT <= @RN
BEGIN
DECLARE @TABLE_NAME NVARCHAR(MAX) = (SELECT TABLE_NAME FROM #TMP1 WHERE ID=@CNT)
SET @SQL = @SQL+ 'SELECT '''+ ISNULL(@TABLE_NAME,'') + ''' AS TABLE_NAME, YEAR(MODIFIEDTIMESTAMP) YEAR,COUNT(1) TOTAL_ROW FROM '+ ISNULL(@TABLE_NAME,'') +' WHERE MODIFIEDTIMESTAMP IS NOT NULL GROUP BY YEAR(MODIFIEDTIMESTAMP)
UNION ALL
'
SET @CNT = @CNT + 1;
END
SET @SQL = LEFT(@SQL,LEN(@SQL)-11) + ') Z'
PRINT @SQL
EXECUTE (@SQL)
SELECT * FROM ##TMP2
PIVOT(
MAX(TOTAL_ROW)
FOR YEAR IN([2016],[2017]) ---------you can make it dynamic by your self
)X
END
CMIIW, 让我知道这是否有用...... 感谢