I use SQL Server 2016.
I need to find table name and column name across all databases on a server.
DECLARE @SQL NVARCHAR(max)
SET @SQL = STUFF((
SELECT '
UNION
SELECT ' + quotename(NAME, '''') + ' as Db_Name, t.Name collate SQL_Latin1_General_CP1_CI_AS as Table_Name,
c.Name as Column_Name
FROM ' + quotename(NAME) + '.sys.tables as t
INNER JOIN ' + quotename(NAME) + '.sys.columns as c ON t.object_id = c.object_id
WHERE t.NAME LIKE ''%'' + @TableName + ''%''
AND c.NAME LIKE ''%'' + @ColumnName + ''%'' '
FROM sys.databases
ORDER BY NAME
FOR XML PATH('')
,type
).value('.', 'nvarchar(max)'), 1, 8, '')
--PRINT @SQL;
EXECUTE sp_executeSQL @SQL
,N'@TableName varchar(30), @ColumnName varchar(30)'
,@TableName = 'Bid'
,@ColumnName = 'bidid'
I'm getting this error
Cannot resolve the collation conflict between "Latin1_General_100_CI_AS_KS_WS" and "SQL_Latin1_General_CP1_CI_AS" in the UNION operation.
Following this thread:
Cannot resolve the collation conflict?
I tried setting collate to 'DATABASE_DEFAULT' by adding to my inner join or where clause, but that did not resolve the error.
By adding to the select list collation as follows: ",c.Name collate SQL_Latin1_General_CP1_CI_AS as Column_Name
" it worked perfectly well