我想根据列名,类型等查询一组表。基本上我不知道表的名称,我想查询数据库中所有能够存储数据的表。
我有这个查询,但我不确定它是否非常有效。我想知道是否有更好的方法。
SELECT O.TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS AS O
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS R1
ON R1.TABLE_NAME = O.TABLE_NAME and R1.COLUMN_NAME = 'Id' and R1.DATA_TYPE = 'uniqueidentifier'
INNER JOIN INFORMATION_SCHEMA.COLUMNS as R2
ON R2.TABLE_NAME = O.TABLE_NAME and R2.COLUMN_NAME = 'Message' and R2.DATA_TYPE = 'nvarchar'
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS R3
ON R3.TABLE_NAME = O.TABLE_NAME and R3.COLUMN_NAME = 'EnteredOn' and R3.DATA_TYPE = 'datetime'
GROUP BY O.TABLE_NAME
此查询目前有效,但我觉得必须有更好的方法。基本上我不希望其他表显示可能有一个名为Id但不包含Message和EnteredOn列的列。
这是表的CREATE TABLE查询。
CREATE TABLE [dbo].[Log](
[Id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[Message] [nvarchar](2048) NULL,
[EnteredOn] [datetime] NOT NULL,
CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
答案 0 :(得分:4)
SELECT table_schema, table_name
FROM information_schema.columns
WHERE COLUMN_NAME = 'Id' AND DATA_TYPE = 'uniqueidentifier'
OR COLUMN_NAME = 'Message' AND DATA_TYPE = 'nvarchar'
OR COLUMN_NAME = 'EnteredOn' AND DATA_TYPE = 'datetime'
GROUP BY table_schema, table_name
HAVING COUNT(COLUMN_NAME) = 3