I want to query a set of tables based on the column name, type, etc. Basically without knowing the name of a table I want to query the database for all tables capable of storing the data into.
I have this query but I'm not sure if it's very efficient. I was wondering if there is a better way.
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
This query currently works but I feel there must be a better way. Basically I don't want other tables showing up that may have a column with the name Id but not the columns Message and EnteredOn.
Here is the CREATE TABLE query for the 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]