我有一个包含150多个表的数据库(让我们称之为DB),(例如:table1,table2等)
问题
I want to loop through all tables and get count of rows by groups, as below
当前方法
As of now I was thinking of appending all tables or doing so manually!
表格结构
name code
A code1
A code2
A code6
A code98
B code1
预期输出
table_name name code count
table1 A code1 100
table1 B code2 941
table2 A code1 98
每个表格的代码
SELECT name, code, count (*) AS count
FROM table1
GROUP BY name, code
答案 0 :(得分:1)
您可以使用SP ForEachTable来执行存储在数据库中的每个表的代码。尝试这样的事情:
sp_MSforeachtable @command1="select '?' AS TABLE_NAME,count(*) from ?"
答案 1 :(得分:1)
如果你想要结果一个结果集,下面的结果将起作用:
CREATE TABLE #Temp
(
tableName VARCHAR(100)
,name VARCHAR(10)
,code VARCHAR(10)
, [Count] INT
)
EXEC sys.sp_MSforeachtable @command1=" insert into #Temp select '?' AS tableName,Name,Code,count(*) from ? group by Name, Code"
SELECT * FROM #Temp
DROP TABLE #temp
作为替代方案,使用动态sql:
CREATE TABLE #Temp
(
tableName VARCHAR(100)
,name VARCHAR(10)
,Code VARCHAR(10)
, [Count] INT
)
DECLARE @TableName VARCHAR(100)
DECLARE tableCursor CURSOR FAST_FORWARD FOR
SELECT name FROM sys.tables WHERE type ='U'
OPEN tableCursor
FETCH NEXT FROM tableCursor INTO @TableName
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE @Query NVARCHAR(MAX)= N'select @table as TableName, Name, Code,Count(*) as [Count] from '+ @tablename + ' Group by Name, Code'
INSERT INTO #Temp
EXEC sp_executesql @Query, N'@table varchar(100)', @table = @TableName
FETCH NEXT FROM tableCursor INTO @TableName
END
CLOSE tableCursor
DEALLOCATE tableCursor
SELECT * FROM #temp
DROP TABLE #temp