无法解决 union 操作中 latin1_general_ci_as 和 sql_latin1_general_cp1_ci_as 之间的排序规则冲突

Posted

技术标签:

【中文标题】无法解决 union 操作中 latin1_general_ci_as 和 sql_latin1_general_cp1_ci_as 之间的排序规则冲突【英文标题】:cannot resolve the collation conflict between latin1_general_ci_as and sql_latin1_general_cp1_ci_as in the union operation 【发布时间】:2016-05-28 12:48:42 【问题描述】:
SELECT   
  f.feature_id,
  f.site_code,
  f.plot_number,
  'ID Error - 7th and 8th characters of ID do not match the Island of the selected Structure, expected value: ' + f.ward_code as message_text,
  'Y' as IsError
FROM feature f
  inner join feature_type ft on f.feature_type_code = ft.feature_type_code AND ft.feature_group_code IN ('FC')
WHERE f.ward_code <> RIGHT(LEFT(f.feature_id, 8),2)

union

SELECT  
  f.feature_id,
  f.site_code,        
  f.plot_number,
  'ID Error - Engineering District do not match the Region of the selected    Structure, expected value: '+ laa.region as message_text,
  'Y' as IsError
FROM feature f
  inner join feature_type ft on f.feature_type_code = ft.feature_type_code AND ft.feature_group_code IN ('FC')
  inner join loc_ase.loc_db.dbo.loc_admin_area laa on f.contract_area_code = laa.contract_area_code 
WHERE f.[area_code] collate SQL_Latin1_General_CP1_CI_AS <> laa.[region] collate SQL_Latin1_General_CP1_CI_AS 

【问题讨论】:

【参考方案1】:

您应该在其中一个排序规则中选择VARCHAR 字段以避免此错误。一个例子:

CREATE TABLE #t1(some_text NVARCHAR(512) COLLATE latin1_general_ci_as);
CREATE TABLE #t2(other_text NVARCHAR(512) COLLATE sql_latin1_general_cp1_ci_as);

SELECT some_text FROM #t1
UNION
SELECT other_text COLLATE latin1_general_ci_as FROM #t2

DROP TABLE #t1;
DROP TABLE #t2;

这不会导致排序错误。将这种工作方式应用于您的查询。

【讨论】:

像往常一样,我总是希望我的首页上出现的所有带有sql标签的问题都是针对sql-server的(忽略标签等等)。这个答案反映了这应该如何在 SQL Server 中完成。

以上是关于无法解决 union 操作中 latin1_general_ci_as 和 sql_latin1_general_cp1_ci_as 之间的排序规则冲突的主要内容,如果未能解决你的问题,请参考以下文章

使用UNION后,ORDER BY 怎样使用

关于SQL union操作的效率问题

UNION ALL、UNION与ORDER BY

UNION 与 UNION ALL 的性能

SQL中Union与Union All的区别

创建一个由几个表组成的视图