带/不带光标的简单Sql过程

时间:2013-07-19 08:38:16

标签: sql sql-server sql-server-2008

请帮我一个简单的程序,比方说Sql Server(2005年,2008年,没关系)。

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

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

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

结果应该是这样的:

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

任何提示?

提前致谢, 波格丹

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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]可以仅过滤所需表格的结果。

答案 2 :(得分:0)

使用CURSORDynamic 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