SQL:计算所有表中的列数,不包括视图

时间:2011-03-01 17:17:25

标签: sql sql-server-2005

我正在创建一个返回每个表中列数的查询,但我想要排除Views。

以下有效但返回查看结果:

SELECT COUNT(*), table_name
FROM INFORMATION_SCHEMA.COLUMNS
Group By table_name

有什么建议吗?

注意:MSSQL 2005 +

4 个答案:

答案 0 :(得分:16)

这假设SQL 2005或更高版本

SELECT 
    t.name,
    count(c.name)
FROM 

    sys.tables t 
    inner join sys.columns c
    ON t.object_id = c.object_id


group by t.name

答案 1 :(得分:4)

这样的事情:

SELECT COUNT(col.column_name), col.table_name
FROM information_schema.columns col
  JOIN information_schema.tables tbl 
       ON tbl.table_name = col.table_name 
          AND tbl.table_schema = col.table_schema
          AND tbl.table_catalog = col.table_catalog
          AND tbl.table_type <> 'VIEW'
GROUP BY col.table_name

答案 2 :(得分:0)

加入INFORMATION_SCHEMA.TABLES以查明该表是否为视图。

SELECT COUNT(col.column_name), tab.table_name 
FROM INFORMATION_SCHEMA.tables tab
JOIN INFORMATION_SCHEMA.COLUMNS col ON col.table_name = tab.table_name
WHERE tab.table_type != 'VIEW'
GROUP BY 2
ORDER BY 2 

答案 3 :(得分:0)

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
<table style="background-color:#9300C4;position:absolute;top:0;left:0;z-index:2;border:1px solid black" border="1" width="100%" >
        <tr>
          <td>
             <div ><a data-toggle="collapse" data-target="#demo"><h7 style="color:#FFFFFF;cursor: pointer;font-weight:600;"> Collapse >></h2></a></div>
             <div id="demo" class="collapse" style="width:100%;background-color:#FF3B29;" >
             
      			<br/>
              		<font face="Verdana, Arial, Helvetica, sans-serif" size="2" color="white" style="margin-left:2%;"> This is for testing purpose. This is for testing purpose. </Font></a>
             	<br/>
               	 	<font face="Verdana, Arial, Helvetica, sans-serif" size="2" color="white" style="margin-left:2%;"> This is for testing purpose. This is for testing purpose. </Font></a>
            	
            </div>
          </td>
        </tr>
  </table>
</body>
</html>

此代码显示表名及其前面的列数。 如果需要,可以添加模式名称。