我这样做了。但不幸的是,在许多表中返回所有。我想在一个独特的表中返回所有内容。也许正在使用" UNION"但我不知道该怎么做。
这是我的代码:
EXEC sp_msforeachdb 'select ''?''AS "DataBase", s.name, t.name AS "Tables",max(si.rows) as "Rows Line"
from [?].sys.tables t inner join [?].sys.schemas s
on t.schema_id = s.schema_id
inner join [?].sys.partitions si on t.object_id = si.object_id
where t.name like "%ATTACH" group by s.name,t.name'`
答案 0 :(得分:0)
您无法在单个查询中执行此操作。
您可以查询sys.databases表以获取所有数据库的临时表,然后对每个数据库运行动态查询,以便将问题中的查询结果存储在另一个临时表中。
然后在最后,您只需选择上一个临时表中的所有行。
答案 1 :(得分:0)
我终于找到了一个解决方案。我只是使用了一个存储过程来获得我正在寻找的结果。所以决定在这里发布答案可能会帮助其他人。
DECLARE @banco_nome nvarchar(MAX), @tabela_nome nvarchar(MAX)
DECLARE @banco_cursor CURSOR
DECLARE @sqlstatement nvarchar(MAX)
DECLARE @count_sql nvarchar(MAX)
DECLARE @total int
DECLARE @RegistrosFotograficos TABLE
(
DatabaseName nvarchar(max),
TableName nvarchar(max),
Total int
)
SET @banco_cursor = CURSOR FORWARD_ONLY FOR
SELECT name FROM sys.databases
OPEN @banco_cursor
FETCH NEXT FROM @banco_cursor INTO @banco_nome
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sqlstatement = 'DECLARE tabela_cursor CURSOR FORWARD_ONLY FOR SELECT TABLE_NAME FROM ' + @banco_nome + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_NAME LIKE ''%ATTACH'' ORDER BY TABLE_NAME'
EXEC sp_executesql @sqlstatement
OPEN tabela_cursor
FETCH NEXT FROM tabela_cursor INTO @tabela_nome
WHILE @@FETCH_STATUS = 0
BEGIN
SET @count_sql = 'USE ' + @banco_nome + '; SELECT @total=COUNT(1) FROM ' + @tabela_nome;
EXECUTE sp_executesql @count_sql, N'@total int OUTPUT', @total=@total OUTPUT
INSERT INTO @RegistrosFotograficos (DatabaseName, TableName, Total) VALUES (@banco_nome, @tabela_nome, @total);
FETCH NEXT FROM tabela_cursor INTO @tabela_nome
END
CLOSE tabela_cursor;
DEALLOCATE tabela_cursor;
FETCH NEXT FROM @banco_cursor INTO @banco_nome
END
CLOSE @banco_cursor;
DEALLOCATE @banco_cursor;
SELECT * FROM @RegistrosFotograficos
答案 2 :(得分:0)
这将列出给定数据库中的所有表以及每个表中的行数。请注意,结果位于名为#results:
的表中set nocount on
declare @curtable sysname
declare @prevtable sysname
declare @curcount int
declare @tsql varchar(500)
if object_ID('tempdb..#curtables','U') is not null
drop table #curtables
select name into #curtables
from sys.objects
where type='U'
order by 1
if object_id('tempdb..#results','U') is not null
drop table #results
create table #results(name sysname,numrows int)
select top 1 @curtable=name from #curtables order by name
while (1=1)
begin
set @tsql = 'select '''+quotename(@curtable) +''',count(*) numrows from '+quotename(@curtable)
print @tsql
insert into #results
exec (@tsql)
set @prevtable= @curtable
select top 1 @curtable = name
from #curtables
where name > @prevtable
order by name
if @curtable=@prevtable
break
端