最近碰到一例因排序规则而导致的冲突问题,运行环境是SQL 2008,具体代码如下:DECLARE @URL VARCHAR(500),
@startdate DATETIME,
@enddate DATETIME,
@Identifier VARCHAR(20);
SELECT @URL = '/articlenet/article.aspx',
@startdate = '2010-02-01',
@enddate = '2010-02-28',
@Identifier = 'id';
SELECTCAST(au.PopulateDate ASdate) AS DateViewed
,qs.Value
,COUNT(1) AS PageViews
,COUNT(
DISTINCTCASEWHEN au.UserId = 6264375 THEN au.FPID
ELSE du.UserGUID END
) AS DistinctUsers
FROM Dim_URL u (NOLOCK)
JOIN dbo.Agg_User_Archive au (NOLOCK)
ON u.URLKey = au.URLKey
JOIN Dim_QueryString qs (NOLOCK)
ON au.AggUserId = qs.AggUserId
JOIN dbo.Dim_UserId du (NOLOCK)
ON du.UserKey = au.UserId
WHERE URL = @URL
AND au.PopulateDate > @startdate
AND au.PopulateDate < @enddate
AND qs.Identifier = @Identifier
GROUPBYCAST(au.PopulateDate ASDATE), Value
ORDERBY DateViewed DESC, Value;
--Msg 457, Level 16, State 1, Line 11
--Implicit conversion of varchar value to varchar cannot be performed because the collation of the value is unresolved due to a collatio
/*该查询是一个已经编写好的查询语句,只是根据需要我们做出了适当的调整。即新增了一个JOIN表Dim_UserId,然后将CASE子句中THEN后
面跟的,原来为FPIDKey更换为FPID,ELSE后面的UserId更换为UserGUID。修改后的批处理中语法检查时并没有发现任何错误。执行时出现
上述错误提示。从错误的提示来分析是因为排序冲突所致,因此查看新增的两个字段是否使用了相同的排序规则。下面是查看语句: */
SELECT o.name,o.object_id,c.name,c.column_id,c.collation_name
FROM sys.columns c
JOIN sys.objects o
ON c.object_id = o.object_id
WHERE o.object_id = OBJECT_ID('dbo.Dim_UserId')
AND c.name = 'UserGUID'
UNION
SELECT o.name,o.object_id,c.name,c.column_id,c.collation_name
FROM sys.columns c
JOIN sys.objects o
ON c.object_id = o.object_id
WHERE o.object_id = OBJECT_ID('dbo.Agg_User_Archive')
AND c.name = 'FPID'
/*
name object_id name column_id collation_name
------------------ ----------- ---------- ----------- ----------------------
Agg_User_Archive 1613248802 FPID 28 Latin1_General_CS_AI
Dim_UserId 1234819461 UserGUID 2 Latin1_General_BIN
*/
--从查询结果中可以看出,原来是因为两个列使用的不同的排序规则,故在count运算时发生了错误。于是修改语句如下,问题解决。下面仅列出被修改过的语句。
COUNT(DISTINCTCASEWHEN au.UserId = 6264375 THEN au.FPID COLLATE DATABASE_DEFAULT
ELSE du.UserGUID COLLATE DATABASE_DEFAULT END
) AS DistinctUsers
以下列出Collate子句的语法:
COLLATE { <collation_name> database_default }
<collation_name> :: = { Windows_collation_name } { SQL_collation_name }
几点注意事项:
一、排序规则可以在以下几个级别指定:
1.创建或更改数据库。
2.创建或更改表列。
3.投影表达式的排序规则。
二、COLLATE 子句只能应用于 char、varchar、text、nchar、nvarchar 和 ntext 数据类型。
--转自