3

请帮我做一个简单的程序,让我们在 Sql Server 上说(2005、2008,没关系)。

我有 table dbo.[columns] with 1000 lines,它们都是数据库中某些特定表名的名称。

底线是我需要为在 dbo.[columns] 中找到的每个表名创建一个解析所有 1000 行表的过程,以执行以下操作

select: select count(*), ''''+[column_name]+'''' from dbo.[column_name]

结果应该是这样的:

count(*)    table_name:
100          employees 
0            ex_employees
25           addresses
10           birthdays

有什么提示吗?

提前致谢, 博格丹

4

3 回答 3

1
SELECT  COUNT(Column_With_List_Of_Table_Names_Here)
        , Column_With_List_Of_Table_Names_Here
FROM    YourDatabase.dbo.YourTable
GROUP BY Column_With_List_Of_Table_Names_Here;
于 2013-07-19T08:49:37.963 回答
0

也许不是你在问什么,但应该得到我认为你想要的结果。您可以使用系统视图来获取每个表的行数,而无需运行COUNT(*)

SELECT i.rowcnt, o.name FROM sysindexes i
LEFT JOIN sys.objects o ON i.id = o.object_id
WHERE indid <2
ORDER BY name

或者

SELECT SUM (row_count) AS ROWS, o.Name AS TableName
FROM sys.dm_db_partition_stats s
LEFT JOIN sys.objects o ON s.object_id = o.object_id AND (index_id=0 or index_id=1)
GROUP BY o.Name

*第二次查询应该更精确

将此查询内部连接到您dbo.[columns]可以仅过滤所需表的结果。

于 2013-07-19T08:54:21.173 回答
0

尝试使用CURSOR And Dynamic sql

CREATE TABLE #temp(count_ int,table_name varchar(50))
DECLARE @column_Name VARCHAR(50)
DECLARE @query VARCHAR(500)

  DECLARE table_cursor CURSOR FOR
  SELECT [column_name] from dbo.[column_name]
  OPEN product_cursor
    FETCH NEXT FROM product_cursor INTO @column_Name

    WHILE @@FETCH_STATUS = 0
    BEGIN

    SET @query='INSERT INTO #temp SELECT'+ @column_Name+',COUNT(*) FROM'+  @column_Name

    EXEC sp_executesql @SQLStatement=@query
    /*this will insert the coresponding table name and its row count to #temp*/

    END

    CLOSE product_cursor
    DEALLOCATE product_cursor


select  * from #temp
于 2013-07-19T08:56:27.563 回答