sql – ORDER BY取决于参数导致错误

前端之家收集整理的这篇文章主要介绍了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.

为什么它会尝试将某些东西转换为日期/时间.有人可以帮忙吗?

解决方法

问题可能是案例的类型转换.以这种方式使用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

问题是该案例具有单个输出类型,在编译查询时确定.此类型基于逻辑组合THEN子句的所有类型.因此,每个then子句的结果将转换为整体类型 – 这就是您的错误发生的地方.

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

猜你在找的MsSQL相关文章