【问题标题】:Loop through multiple tables to see if a column exists?循环遍历多个表以查看列是否存在?
【发布时间】:2019-08-05 17:33:30
【问题描述】:

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

目前为止

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

【问题讨论】:

  • 这似乎过于复杂。您应该能够加入系统表和列列表以返回系统表中表列表中没有该列名的结果
  • Errors Here ...请显示错误信息。
  • @Sami 它只是说语法不正确
  • 如果只需要打印表格的值,为什么不使用FOR XML PATHSTRING_AGG生成列表并将值设置为变量,然后打印变量的值?

标签: sql-server tsql except ssms-2016


【解决方案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'

【讨论】:

    【解决方案2】:

    这应该返回所有表中没有名称为“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'
    )
    

    【讨论】:

      猜你喜欢
      • 2011-06-25
      • 1970-01-01
      • 2011-03-06
      • 1970-01-01
      • 2013-11-30
      • 2018-05-27
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多