查找每个列名称的行数

时间:2019-03-14 16:21:26

标签: sql sql-server

我写了这个简短的脚本,可以在SQL Server数据库中找到特定的列名:

SELECT
    sys.columns.name AS ColumnName,
    tables.name AS TableName
FROM
    sys.columns
JOIN 
    sys.tables ON sys.columns.object_id = tables.object_id
WHERE
    sys.columns.name LIKE '%ColumnName%'

我想添加另一列结果,其中每列的行数。

2 个答案:

答案 0 :(得分:0)

SELECT
  sys.columns.name AS ColumnName,
  tables.name AS TableName, Totals.Total

FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = tables.object_id 
  JOIN
    (SELECT COUNT(*) total, sys.columns.name FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = tables.object_id
  GROUP BY sys.columns.name
    ) Totals
    on Totals.name = sys.columns.name
WHERE
  sys.columns.name LIKE '%ColumnName%'

这将返回所有表中一列存在的次数

答案 1 :(得分:0)

假设没有任何分区表:

USE [SpecificDatabank]
SELECT
  sys.columns.name AS ColumnName,
  sys.tables.name AS TableName,
  sys.partitions.rows AS [Rows]
FROM
  sys.columns
JOIN sys.tables ON
  sys.columns.object_id = sys.tables.object_id
JOIN sys.partitions ON
  sys.tables.object_id = sys.partitions.object_id and sys.partitions.index_id in (0,1)
WHERE
  sys.columns.name LIKE '%ColumnName%'