我需要sql脚本来检查,从数据库中有多少表有数据,有多少表是空的?
答案 0 :(得分:0)
试试这个:
USE dbName
SELECT COUNT(*) from information_schema.tables
WHERE table_type = 'base table'
答案 1 :(得分:0)
答案 2 :(得分:0)
请尝试以下方法......
CREATE PROCEDURE EmptyFullTableCounter AS
BEGIN
DECLARE @fldNameValue VARCHAR( 64 );
DECLARE @sqlStatementString varchar( 200 );
DECLARE @loopIndex INT = 1;
DECLARE @recordCount INT;
DROP TABLE IF EXISTS tempTblTableNames;
CREATE TABLE tempTblTableNames
(
fldName VARCHAR( 64 ),
fldCount INT
);
INSERT INTO tempTblTableNames ( fldName,
fldCount )
SELECT table_name,
0
FROM INFORMATION_SCHEMA.TABLES
WHERE table_type = 'BASE TABLE'
AND table_catalog = 'UserAccessAccounts001'
AND table_name != 'tempTblTableNames';
SET @recordCount = ( SELECT COUNT( * )
FROM tempTblTableNames );
WHILE @loopIndex <= @recordCount
BEGIN
SET @fldNameValue = ( SELECT fldName
FROM ( SELECT fldName,
ROW_NUMBER() OVER ( ORDER BY fldName ) AS recordNumber
FROM ( SELECT fldName
FROM tempTblTableNames
) AS fldNamesFinder
) AS fldNamesWithRowNumber
WHERE recordNumber = @loopIndex );
SET @sqlStatementString = 'UPDATE tempTblTableNames ' +
'SET fldCount = ( SELECT COUNT( * ) ' +
' FROM ' +
@fldNameValue +
' ) ' +
'WHERE fldName = ''' +
@fldNameValue +
''';';
EXEC ( @sqlStatementString );
SET @loopIndex = @loopIndex + 1;
END
SELECT SUM( IIF( fldCount > 0, 1, 0 ) ) AS Haves,
SUM( IIF( fldCount = 0, 1, 0 ) ) AS HaveNots
FROM tempTblTableNames;
DROP TABLE tempTblTableNames;
END
此过程首先创建一个表来保存每个表的名称,然后使用以下语句填充它...
INSERT INTO tempTblTableNames ( fldName,
fldCount )
SELECT table_name,
0
FROM INFORMATION_SCHEMA.TABLES
WHERE table_type = 'BASE TABLE'
AND table_catalog = 'UserAccessAccounts001'
AND table_name != 'tempTblTableNames';
请注意,上述声明从我们的表格列表中排除了tempTblTableNames
。
然后,该过程存储变量@recordCount
中记录总数的计数。此值用作WHILE
循环的标记值,该循环从tempTblTableNames
中提取每个表名,并在其周围构建一个语句,该语句将更新tempTblTableNames
中该表名的关联计数。然后执行该语句并迭代循环索引。
循环完成后,执行最终SELECT
语句,将SUM()
与IIF()
结合使用,以计算具有记录的表的数量和不具有记录的表的数量有记录。
如果您有任何问题或意见,请随时发表评论。