跨多个SQL Server数据库计算行数

时间:2012-12-28 18:12:24

标签: sql-server

我正在尝试从SQL Server实例中的每个数据库中计算所有名为tblDoc的表的行。

我试过了,但显然你无法在游标中访问或声明变量:

DECLARE @dbname nvarchar(1000);
DECLARE @sqlCommand NVARCHAR(1000) 
DECLARE @results TABLE(numberOfDocuments bigint);
DECLARE c1 CURSOR READ_ONLY
FOR 
SELECT '[' + name + ']'  FROM sys.databases WHERE name <> 'tempdb' 
OPEN c1 
FETCH NEXT FROM c1 
INTO @dbname 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    SET @sqlCommand = 'INSERT INTO results SELECT COUNT(ID) FROM ' + @dbname + '.dbo.tblDoc;';
    print @sqlCommand;
    EXECUTE sp_executesql @sqlCommand 
FETCH NEXT FROM c1 
INTO @dbname 
END
CLOSE c1 
DEALLOCATE c1 

SELECT COUNT(numberOfDocuments) from @results;

2 个答案:

答案 0 :(得分:4)

使用Temp表

DECLARE @dbname nvarchar(1000);
DECLARE @sqlCommand NVARCHAR(1000) 
CREATE TABLE #results (numberOfDocuments bigint);
DECLARE c1 CURSOR READ_ONLY
FOR 
SELECT '[' + name + ']'  FROM sys.databases WHERE name <> 'tempdb' 
OPEN c1 
FETCH NEXT FROM c1 
INTO @dbname 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    SET @sqlCommand = 'INSERT INTO #results SELECT COUNT(ID) FROM ' + @dbname + '.dbo.tblDoc;';
    print @sqlCommand;
    EXECUTE sp_executesql @sqlCommand 
FETCH NEXT FROM c1 
INTO @dbname 
END
CLOSE c1 
DEALLOCATE c1 

SELECT COUNT(numberOfDocuments) from #results;

拉​​吉

答案 1 :(得分:0)

如果您要从给定服务器中的所有数据库中查找所有表计数,那么下面的解决方案非常简单。

DECLARE @dbname nvarchar(1000);
DECLARE @sqlCommand NVARCHAR(1000) 
drop table if exists ##temp
create table ##temp (dbname varchar(500),schemaname varchar(500),tablename varchar(500),counts int)
DECLARE c1 CURSOR READ_ONLY
FOR 
SELECT name FROM master.sys.databases  WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb');
OPEN c1 
FETCH NEXT FROM c1 
INTO @dbname 
WHILE @@FETCH_STATUS = 0 
BEGIN 
    SET @sqlCommand = 'INSERT INTO ##temp'+'

SELECT 
    
    '''+@dbname+''' as databasename,    
    s.name AS schemaname,
    t.name AS tablename,
    p.rows AS rowcounts

FROM '+@dbname+'.sys.tables t
INNER JOIN '+@dbname+'.sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN '+@dbname+'.sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN '+@dbname+'.sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN '+@dbname+'.sys.schemas s ON t.schema_id = s.schema_id
WHERE t.NAME NOT LIKE ''dt%'' 
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
    
GROUP BY 
t.name, s.name, p.Rows
'
;
    print @sqlCommand;
    EXECUTE sp_executesql @sqlCommand 
FETCH NEXT FROM c1 
INTO @dbname 
END
CLOSE c1 
DEALLOCATE c1 

select * from ##temp