Count number of columns in SQL Server

▼魔方 西西 提交于 2019-12-08 02:56:37

问题


Is there a way to know the number of columns in SQL, something like count()...?


回答1:


one way

select count(*) from sys.columns 

another

select count(*) from information_schema.columns

The bottom one does not have the system tables

by table

select count(*),table_name from information_schema.COLUMNS
GROUP BY table_name

tables only

select count(*),c.table_name 
from information_schema.COLUMNS c
JOIN information_schema.tables t ON c.TABLE_NAME = t.TABLE_NAME
AND c.TABLE_Schema = t.TABLE_Schema
WHERE TABLE_TYPE = 'base table'  
GROUP BY c.table_name

views only

select count(*),c.table_name 
from information_schema.COLUMNS c
JOIN information_schema.tables t ON c.TABLE_NAME = t.TABLE_NAME
AND c.TABLE_Schema = t.TABLE_Schema
WHERE TABLE_TYPE = 'view'  
GROUP BY c.table_name



回答2:


Select Count(*) From INFORMATION_SCHEMA.COLUMNS Where TABLE_NAME='YourTableName'



回答3:


This should work across multiple RDBMS's:

select count(*) from INFORMATION_SCHEMA.COLUMNS

And if you want to get fancy:

select TABLE_NAME,
       count(*)
  from INFORMATION_SCHEMA.COLUMNS
group by TABLE_NAME
order by TABLE_NAME



回答4:


For a particular table:

select * from sys.tables
where name = 'mytable';

Get the object_id from this, then use:

select count(*) from sys.columns
where object_id = 831342026;



回答5:


SELECT count(*)
FROM Database_Name.INFORMATION_SCHEMA.COLUMNS
where table_name = 'Table_Name'

to Run 2 steps are needed : 1- choose the database_Name to your database name 2- Change Your Table Name Notes: if you didn't write database_Name like

from INFORMATION_SCHEMA.COLUMNS 

retrieves System database only



来源:https://stackoverflow.com/questions/5902764/count-number-of-columns-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!