遍历多个表以查看是否存在一列?

时间:2019-03-14 17:48:28

标签: sql-server tsql except ssms-2016

我有一个临时表,其中包含表名列表 我需要遍历这些表以查看此列是否存在。如果没有,则打印出不存在的表

到目前为止我有

CREATE TABLE #ListOfTables (
   [TableName] varchar(max)
)
INSERT INTO #ListOfTables
   ([TableName])
  (SELECT TableName from dbo.CustomTableAttributes)

-- Statement
DECLARE @stm nvarchar(max)
SET @stm = N''

IF EXISTS(SELECT 1 FROM sys.columns 
          WHERE Name = N'BegDt'
 Errors Here --> AND Object_ID = Object_ID(N''+ ***Select [TableName] FROM #ListOfTables*** +''))

Begin
'Do Work here'
End

2 个答案:

答案 0 :(得分:1)

这应该返回表中没有名称为“ ID”的列的所有表。只需将“ ID”更改为所需即可。

SELECT * 
FROM sys.tables TBL
-- this reverses the logic and returns all tables that do not exist in the below list
WHERE TBL.object_id NOT IN (
    -- this selects all the tables that have that column in the table structure
    SELECT TBL.object_id
    FROM sys.tables TBL
    INNER JOIN sys.columns COL ON TBL.object_id = col.object_id
    WHERE col.name = 'ID'
)

答案 1 :(得分:1)

请尝试这样

存在:

SELECT table_name 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE table_name in (SELECT TableName from dbo.CustomTableAttributes)
    AND column_name = 'BegDt'

不存在:

SELECT TableName from dbo.CustomTableAttributes
Except    
SELECT table_name 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE table_name in (SELECT TableName from dbo.CustomTableAttributes)
    AND column_name = 'BegDt'