SQL Server snippets
How to find all tables with a specified COLUMN
Example 1
Let's suppose to have three tables Food1
, Food2
and Food3
and we want to find all tables with Code
column.
CREATE TABLE Food1(
[Group] [nvarchar](100) NULL,
[Quantity] [int] NOT NULL,
[Color] [nvarchar](50) NULL,
) ON [PRIMARY];
CREATE TABLE Food2(
[Code] [nvarchar](50) NOT NULL,
[Quantity] [int] NOT NULL,
[Color] [nvarchar](50) NULL,
) ON [PRIMARY];
CREATE TABLE Food3(
[Code] [nvarchar](50) NOT NULL,
[Group] [nvarchar](100) NULL,
[Quantity] [int] NOT NULL,
) ON [PRIMARY];
SELECT A.name AS 'ColumnName',B.name AS 'TableName',B.object_id AS 'ID'
FROM sys.columns A
INNER JOIN sys.tables B
ON A.object_id = B.object_id
WHERE A.name LIKE '%Code%'
ORDER BY TableName,ColumnName;
You can find an interactive version of this example following this link .