我正在尝试编写一个查询,在该查询中,我可以检查某个数据库中的所有表中是否都存在某些列名。为了避免困难,我试图一次访问所有的表,并检查表中是否存在列。我能够找到下面的代码来获得表名:
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG='SAMPLE_DB_NAME' 我无法进入每个表并检查列名。
如果有人可以帮助我进行查询,进入每个表并检查列名,这些列名对于所有表都是恒定的。
发布于 2019-03-13 18:34:50
尝尝这个
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 发布于 2019-03-13 18:36:55
下面的查询将列出不存在任何给定特定字段的所有表名。
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')发布于 2019-03-13 18:44:32
--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'
ENDhttps://stackoverflow.com/questions/55139649
复制相似问题