Cast collation of nvarchar variables in t-sql

与世无争的帅哥 提交于 2019-12-05 08:50:29

问题


I need to change the collation of an nvarchar variable. By documentation:

(...) 3. The COLLATE clause can be specified at several levels. These include the following:

Casting the collation of an expression. You can use the COLLATE clause to apply a character expression to a certain collation. Character literals and variables are assigned the default collation of the current database. Column references are assigned the definition collation of the column. For the collation of an expression, see Collation Precedence (Transact-SQL).

However I can't figure out the correct syntax for the usage of CAST(), CONVERT() or variable declaration with DECLARE for this purpose.


回答1:


SELECT CAST('abc' AS varchar(5)) COLLATE French_CS_AS



回答2:


CAST or CONVERT is superfluous!

SELECT N'abc' COLLATE French_CS_AS

It is superfluous because just changing the collation does not change the data type NVARCHAR.




回答3:


If you are changing between 2 and 1 byte, or vice-ver-sa, character encodings then CAST or Convert is necessary. It is not superfluous in these cases.

When the source column is a 2 byte character sequence (nchar, nvarchar) and the selection projection is required to be a single byte character (char, varchar), you should specify the cast and convert. Apply the collation conversion before the casting between the type systems.

SELECT CAST(N'ФBC' COLLATE SQL_Latin1_General_CP1_CI_AS as varchar(10)) AS ProjectedSingleByte



回答4:


If you would like to compare or join two columns of different collation this could help. In my case I had to compare two columns with one using 'SQL_Latin1_General_CP1_CI_AS' and the other using 'Latin1_General_CP1_CI_AS'.

I simply used this option where i join these two.

on A.Person = B.NAME collate database_default



来源:https://stackoverflow.com/questions/1631936/cast-collation-of-nvarchar-variables-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!