如何根据特定条件从所有表中获取行计数

时间:2012-09-07 18:30:48

标签: sql-server-2008 tsql

我可以使用此查询获取所有表的行数。

    SELECT '[' + SCHEMA_NAME(t.schema_id) + '].[' + t.name + ']' AS fulltable_name, SCHEMA_NAME(t.schema_id) AS schema_name, t.name AS table_name,
    i.rows
    FROM sys.tables AS t INNER JOIN
    sys.sysindexes AS i ON t.object_id = i.id AND i.indid < 2

**AND
t.name.programID = 4**

但是我需要计算programID = n的所有行 将粗体线添加到where子句

时,我一直收到以下错误

无法在nvarchar上调用方法。 非常需要任何帮助 安迪

2 个答案:

答案 0 :(得分:1)

无法像属性一样访问示例中的表名。它只是一个字符串而不是表本身。我已经构建了一个可能适合您的解决方案。感觉有点像黑客,但它会让你在路上。

DECLARE @Value INT, @Column_Name VARCHAR(MAX)

SELECT @Value = 4, @Column_Name = 'ProgramId'

IF OBJECT_ID(N'tempdb..#Results',N'U') IS NOT NULL
            DROP TABLE #Results

SELECT  '[' + SCHEMA_NAME(t.schema_id) + '].[' + t.name + ']' AS fulltable_name, SCHEMA_NAME(t.schema_id) AS     schema_name, t.name AS table_name,
i.rows [Row_Count]
INTO #Results
FROM sys.tables AS t INNER JOIN
sys.sysindexes AS i ON t.object_id = i.id AND i.indid < 2
INNER JOIN information_schema.COLUMNS  C ON t.name = c.TABLE_NAME AND SCHEMA_NAME(t.schema_id)= c.TABLE_SCHEMA  
WHERE C.COLUMN_NAME = @Column_Name

DECLARE @SQL VARCHAR(MAX)

SELECT @SqL = COALESCE(@SqL +' UNION ',' ')  + 'SELECT '''+ fulltable_name + ''', COUNT(*) FROM ' +     fulltable_name +     ' where ' + @Column_Name + ' = ' + CAST(@Value AS VARCHAR(1000))+ ' GROUP BY ' + @Column_Name     + ' '
FROM #Results

PRINT(@SqL)
EXEC (@SqL)

IF OBJECT_ID(N'tempdb..#Results',N'U') IS NOT NULL
            DROP TABLE #Results

答案 1 :(得分:0)

您确定数据库中的所有表都有“programID”列吗?如果是这样的话......试试这个

exec sp_MSforeachtable 'SELECT ''?'' AS TableName,COUNT(*) AS cnt FROM ? WHERE programID = 4'

修改:此查询将跳过计算没有“programID”列

的表
CREATE TABLE #t (table_name Varchar(500), record_count int)

INSERT INTO #t (table_name,record_count)
exec sp_MSforeachtable '
     IF EXISTS(SELECT * FROM sys.columns WHERE name = ''programID'' 
             and object_id = object_id(''?''))
     EXEC(''SELECT ''''?'''' AS TableName,COUNT(*) AS cnt FROM ? WHERE programID = 4'')'

SELECT * FROM #t