我试图写一个查询,我可以检查数据库中的所有表中是否存在某些列名。为了避免困难,我试图一次访问所有表并检查表中是否存在列。我能够找到下面的代码来获取表名:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='SAMPLE_DB_NAME'
我无法进入每个表并检查列名称。
如果任何人可以帮助我查询进入每个表并检查所有表的常量列名称。
试试这个
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
--List of tables
SELECT * FROM sys.tables
--List of Columns
SELECT * FROM sys.columns
--List of Columns Tables joined
SELECT tbl.[name] AS TableName, clm.[name] AS ColumnName FROM sys.tables as tbl INNER JOIN sys.columns as clm ON tbl.[object_id] = clm.[object_id]
-You can check with the column name if the column exist in all tables
USE MyDataBase
DECLARE @TableCount INT
DECLARE @FoundTables INT
SET @TableCount = ( SELECT COUNT(*) FROM sys.tables)
SET @FoundTables = ( SELECT COUNT(DISTINCT(tbl.[name])) AS NumberOfTables FROM sys.tables as tbl INNER JOIN sys.columns as clm ON tbl.[object_id] = clm.[object_id] WHERE clm.[name] = 'YourColumnName')
IF @FoundTables = @TableCount
BEGIN
PRINT 'The column is present in all tables'
END
ELSE
BEGIN
PRINT 'The column is not present in all tables'
END
使用此查询,您可以获取所有表中的所有列
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')
)
以下查询将列出所有不存在任何给定特定字段的表名。
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')