用TSQL查找一个数据库的或者一个表(视图)的字段的collation设置

浏览: 1335

在SQL SERVER中每个数据库都有自己的字符集设置(collation, 也叫排序设置), 那么在试图join或者union来自使用不同collation的数据库表时就会收到错误提示, 比如这样:

In SQL Server, each database may use different Collation setting than others, an error message as follows could pop up when trying to join or union two tables utilizing different Collations.

--table1使用Chinese_PRC_CI_AS
--table2使用SQL_Latin1_General_CP1_CI_AS

SELECT *
FROM tablel
LEFT JOIN table2
ON table1.keycolumn = table2.keycolumn

--------------------------------------------Msg 468, Level 16, State 9, Line 4

无法解决 equal to 运算中 "Chinese_PRC_CI_AS" 和 "SQL_Latin1_General_CP1_CI_AS" 之间的排序规则冲突。


解决的方法很简单, 在语句中需要转换的字段名后添加 collate语句就可以了.

It's quite easy to get resolved - inserting Collate clue statement right after the columns which need to be transferred to another collation

--根据你的需要,转换其中一个table的collation就可以了
--下面例子就是把使用中文字符集的字段转换成英文

SELECT *
FROM tablel
LEFT JOIN table2
ON table1.keycolumn COLLATE SQL_Latin1_General_CP1_CI_AS = table2.keycolumn

另外如果你使用的是union语句, 那么在select后面提及的column也需要使用collate语句, 比如这样

If you need to use UNION, Collate statement needs to be added for the column mentioned in SELECT statement

SELECT keycolumn COLLATE SQL_Latin1_General_CP1_CI_AS 
FROM tablel
UNION ALL
SELECT keycolumn
FROM table2

当然, 还可能会出现种情况, 你并不知道某个字段的collation怎么办? 用下图的语句, 配合sys.columns和sys.objects系统表就可以查出来了. 需要注意的是, 如果字段不是字符串型, 那么collation就会是null

Of course, sometimes you just have no idea what collation has been used for a specified column, what to do? The following screenshot suggests a way out by using two system tables altogether- sys.column and sys.objects. But one thing to be noted is that NULL will be returned for the NON-String columns, such as varchar and nvarchar 

161128-2.png


最后是用tsql的databasepropertyex来查某个数据库的collation设置, 当然更简单的办法是直接到数据库的属性页面去看 : )

One last thing is how to check collation of a database in TSQL, the following screenshot shows how to do it with function "databasepropertyex", but a more convenient way out is check it in database property page.

161128-1.png

推荐 4
本文由 Naralee 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册