ORDER BY取决于参数导致错误

时间:2015-06-10 14:16:15

标签: sql sql-server sql-order-by

我有一个存储过程,它通过依赖参数来启动订单:

DROP PROCEDURE [dbo].[GetUsersByClusterAndUserName]
  GO
CREATE PROCEDURE [dbo].[GetUsersByClusterAndUserName]
    @SortField [nvarchar] (256) = 'UserName',
    @SortOrder [int] = 0
AS
    SELECT * FROM [User] 
    ORDER BY
    CASE WHEN @SortOrder = 0 THEN
        CASE 
            WHEN @SortField = 'UserName' THEN User_UserName 
            WHEN @SortField = 'LastLoginDate' THEN User_LastLoginDate 
            WHEN @SortField = 'CreationDate' THEN User_CreationDate END
    END ASC,    
    CASE WHEN @SortOrder = 1 THEN
        CASE
            WHEN @SortField = 'UserName' THEN User_UserName 
            WHEN @SortField = 'LastLoginDate' THEN User_LastLoginDate
            WHEN @SortField = 'CreationDate' THEN [User_CreationDate] END
    END DESC
RETURN 0
GO

然而......如果我按照这样的程序调用:

EXEC dbo.GetUsersByClusterAndUserName @SortOrder=1, @SortField='UserName'

我收到以下错误:

Msg 241, Level 16, State 1, Procedure GetUsersByClusterAndUserName, Line 7
Conversion failed when converting date and/or time from character string.

为什么会尝试将某些内容转换为日期/时间。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:4)

问题可能是来自case的类型转换。以这种方式使用order by时,请使用多个case语句:

ORDER BY (CASE WHEN @SortOrder = 0 AND @SortField = 'UserName' THEN User_UserName END),
         (CASE WHEN @SortOrder = 0 AND @SortField = 'User_LastLoginDate' THEN User_LastLoginDate END),
         (CASE WHEN @SortOrder = 0 AND @SortField = 'User_CreationDate' THEN User_CreationDate END),
         (CASE WHEN @SortOrder = 1 AND @SortField = 'UserName' THEN User_UserName END) DESC,
         (CASE WHEN @SortOrder = 1 AND @SortField = 'User_LastLoginDate' THEN User_LastLoginDate END) DESC,
         (CASE WHEN @SortOrder = 1 AND @SortField = 'User_CreationDate' THEN User_CreationDate END) DESC

问题是case有一个输出类型,在编译查询时确定。此类型基于逻辑组合THEN子句的所有类型。因此,每个then子句的结果将转换为整体类型 - 这就是您的错误发生的位置。

您可以阅读有关数据优先级规则here的信息。但解决方案很简单:使用多个case语句。