如何检查数据库中所有表中存在的列名

时间:2019-03-13 10:29:21

标签: sql-server ssms sql-server-2016

我试图编写一个查询,在其中可以检查数据库的所有表中是否存在某些列名。 为了避免麻烦,我试图一次访问所有表,并检查表中是否存在列。 我能够找到下面的代码来获取表名:

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='SAMPLE_DB_NAME'  

我无法进入每个表并检查列名。

如果有人可以帮助我进行查询以进入每个表并检查所有表中恒定的列名。

4 个答案:

答案 0 :(得分:0)

尝试一下

SELECT  TABLE_CATALOG,
        TABLE_NAME,
        COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_CATALOG='SAMPLE_DB_NAME' 
AND CHARINDEX('Status',COLUMN_NAME) = 1 -- Specify the column name to check the column is existed
                                        --- in the datbase of all available tables 

答案 1 :(得分:0)

以下查询将列出所有不存在任何给定特定字段的表名。

SELECT distinct TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE  TABLE_CATALOG='testdb' 
and TABLE_NAME not in(
select object_name(object_id) ObjectName from sys.COLUMNS where name  in ('YourfieldName1', 'YourfieldName2')

下面的查询将列出所有表名称,可在其中找到指定的字段。

select object_name(object_id) ObjectName, * 
from sys.COLUMNS where name  in ('YourfieldName1', 'YourfieldName2')

答案 2 :(得分:0)

public function parent()
{
    return $this->belongsTo('App\Person', 'parent_id');
}

public function child()
{
    return $this->hasMany('App\Person', 'parent_id');
}

答案 3 :(得分:0)

通过此查询,您可以获取所有表中存在的所有列

WITH DistinctColumnNames AS (
    SELECT DISTINCT Column_Name 
    FROM INFORMATION_SCHEMA.COLUMNS C
    JOIN INFORMATION_SCHEMA.TABLES T ON C.TABLE_SCHEMA = T.TABLE_SCHEMA AND C.TABLE_NAME = T.TABLE_NAME AND C.TABLE_CATALOG = T.TABLE_CATALOG
    WHERE T.TABLE_TYPE = 'BASE TABLE' AND T.TABLE_CATALOG='SAMPLE_DB_NAME' AND T.TABLE_SCHEMA = 'dbo' AND T.TABLE_NAME NOT LIKE 'sys%'
)
SELECT COLUMN_NAME
FROM DistinctColumnNames DC
WHERE NOT EXISTS (
    SELECT 1 
    FROM INFORMATION_SCHEMA.TABLES T
    WHERE T.TABLE_TYPE = 'BASE TABLE' AND T.TABLE_CATALOG='SAMPLE_DB_NAME' AND T.TABLE_SCHEMA = 'dbo' AND T.TABLE_NAME NOT LIKE 'sys%'
    AND NOT EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS C
        WHERE C.TABLE_NAME = T.TABLE_NAME AND C.COLUMN_NAME = DC.COLUMN_NAME
         AND T.TABLE_CATALOG='SAMPLE_DB_NAME' AND T.TABLE_SCHEMA = 'dbo')
)