Skip to content

Instantly share code, notes, and snippets.

@GeorgeDellinger
Last active December 17, 2015 10:28
Show Gist options
  • Select an option

  • Save GeorgeDellinger/5594993 to your computer and use it in GitHub Desktop.

Select an option

Save GeorgeDellinger/5594993 to your computer and use it in GitHub Desktop.
sp_FindColums from current database along with any synonym tables.
USE [master]
GO
/****** Object: StoredProcedure [dbo].[sp_FindColumnsIncludeSynonyms] Script Date: 05/17/2013 08:02:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
if exists (select * from sysobjects where id = object_id(N'[dbo].[sp_FindColumnsIncludeSynonyms]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[sp_FindColumnsIncludeSynonyms]
GO
CREATE Procedure [dbo].[sp_FindColumnsIncludeSynonyms]
@Column varchar(max)
AS
DECLARE @sql VARCHAR(MAX), @ServerName VARCHAR(MAX), @dbName VARCHAR(MAX)
SET @sql = 'SELECT ''local'' as server, table_catalog, table_schema, table_name, column_name, data_type, character_maximum_length as max_length, 0 as synonym ' +
'FROM information_schema.columns '+
'WHERE column_name LIKE ''%'+@Column+'%'' and objectproperty(object_id(table_name), ''IsTable'') = 1 ';
DECLARE ColumnCursor CURSOR FOR
SELECT DISTINCT
SUBSTRING(COALESCE(PARSENAME(base_object_name,4),@@servername),
CHARINDEX('.', COALESCE(PARSENAME(base_object_name,4),@@servername)) + 1,
LEN(COALESCE(PARSENAME(base_object_name,4),@@servername))) as ServerName,
COALESCE(PARSENAME(base_object_name,3),DB_NAME(DB_ID())) AS dbName
FROM sys.synonyms
WHERE COALESCE(PARSENAME(base_object_name,3),DB_NAME(DB_ID())) <> DB_NAME()
ORDER BY serverName,dbName
OPEN ColumnCursor
FETCH NEXT FROM ColumnCursor INTO @ServerName, @dbName
WHILE @@FETCH_STATUS = 0
BEGIN
set @sql = @sql +
'UNION ' +
'SELECT '''+@ServerName+''' as server, table_catalog, table_schema, table_name, column_name, data_type, character_maximum_length as max_length, 1 as synonym ' +
'FROM ['+@ServerName+'].['+@dbName+'].Information_schema.columns ' +
'WHERE column_name LIKE ''%'+@Column+'%'' '
FETCH NEXT FROM ColumnCursor INTO @ServerName, @dbName
END
set @sql = @sql + 'ORDER BY synonym, server, table_schema, table_name;'
CLOSE ColumnCursor
DEALLOCATE ColumnCursor
exec (@sql)
GO
EXEC sys.sp_MS_marksystemobject sp_FindColumnsIncludeSynonyms
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment