尝试查找特定表和列

时间:2018-04-19 15:53:35

标签: sql-server collation cross-database findname

我使用SQL Server 2016.

我需要在服务器上的所有数据库中查找表名和列名。

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'

我收到此错误

  

无法在UNION操作中解决“Latin1_General_100_CI_AS_KS_WS”和“SQL_Latin1_General_CP1_CI_AS”之间的排序规则冲突。

遵循这个主题:

Cannot resolve the collation conflict?

我尝试通过添加到我的内部联接或where子句将collat​​e设置为“DATABASE_DEFAULT”,但这并没有解决错误。

1 个答案:

答案 0 :(得分:2)

通过添加到选择列表排序规则,如下所示:" ,c.Name collate SQL_Latin1_General_CP1_CI_AS as Column_Name"它工作得很好