1

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

我试过这个,但显然你不能访问或声明游标中的变量:

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;
4

2 回答 2

4

改用临时表

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;

拉吉

于 2012-12-28T18:20:41.387 回答
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
于 2021-01-25T18:48:18.447 回答