遍历多个表,看某列是否存在?
Loop through multiple tables to see if a column exists?
我有一个临时文件 table,其中包含 table 个名称的列表
我需要遍历这些 table 以查看此列是否存在。如果不是,则在不存在的地方打印出 table
到目前为止我有
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
这应该 return 在 table 中没有名称为 'ID' 的列的所有 table。只需将 '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'
)
请尝试这样的操作
存在:
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'
我有一个临时文件 table,其中包含 table 个名称的列表 我需要遍历这些 table 以查看此列是否存在。如果不是,则在不存在的地方打印出 table
到目前为止我有
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
这应该 return 在 table 中没有名称为 'ID' 的列的所有 table。只需将 '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'
)
请尝试这样的操作
存在:
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'