检索具有特定列名称的所有非空表

时间:2018-04-24 05:27:11

标签: sql sql-server

我需要获取所有非空的表并保留特定的列名。我看到了一些关于每个任务的教程,但没有结合在一起,有人可以建议如何实现这个目标吗?

表中特定列名的查询:

Select *
From INFORMATION_SCHEMA.COLUMNS
Where COLUMN_NAME like '%company%' 

查询所有非空表:

SELECT r.table_name, r.row_count, r.[object_id]
FROM sys.tables t
INNER JOIN (
SELECT OBJECT_NAME(s.[object_id]) table_name, SUM(s.row_count) row_count, s. 
[object_id]
FROM sys.dm_db_partition_stats s
WHERE s.index_id in (0,1)
GROUP BY s.[object_id]) 
r on t.[object_id] = r.[object_id]
WHERE r.row_count > 0
ORDER BY r.table_name;

任何帮助都会得到满足,谢谢。

1 个答案:

答案 0 :(得分:0)

使用结果之间的联接来获取最终结果。

select a11.table_name, a11.row_count, a11.[object_id]
from (SELECT r.table_name, r.row_count, r.[object_id]
FROM sys.tables t
INNER JOIN (
SELECT OBJECT_NAME(s.[object_id]) table_name, SUM(s.row_count) row_count, s. 
[object_id]
FROM sys.dm_db_partition_stats s
WHERE s.index_id in (0,1)
GROUP BY s.[object_id]) 
r on t.[object_id] = r.[object_id]
WHERE r.row_count > 0
) a11
join 
(Select table_name
From INFORMATION_SCHEMA.COLUMNS
Where COLUMN_NAME like '%company%' 
) a12
on a11.table_name = a12.table_name
order by a11.table_name