我正在尝试计算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;