算术溢出错误按[TimeStamp](列名称)排序时

时间:2017-09-05 06:34:50

标签: sql sql-server

我收到了错误:

Arithmetic overflow error converting expression to data type smalldatetime

请注意我已经搜索了这个主题,但我的错误是独一无二的,因为它是由ORDER BY子句引起的。有问题的行是 WHEN 'TimeStamp' THEN [MyTable].[TimeStamp]

当我对这些TimeStamp发表评论时,查询已成功执行,但我仍需要一个解决方案来排序我的TimeStamp列(无法重命名该列)。

这是我的疑问:

SELECT
    Id,
    [TimeStamp],
    StatusCode
FROM 
    (
    SELECT 
        TOP (@EndRecord) ROW_NUMBER() OVER 
        (       
        ORDER BY
            CASE @SortDirection
                WHEN 'Desc' THEN
                    CASE @SortColumn                        
                        WHEN 'Id' THEN [MyTable].[Id]
                        WHEN 'TimeStamp' THEN [MyTable].[TimeStamp]
                        WHEN 'StatusCode' THEN [MyTable].[StatusCode]

                        ELSE [MyTable].[TimeStamp]
                    END
            END DESC,
            CASE @SortDirection
                WHEN 'Asc' THEN
                    CASE @SortColumn                        
                        WHEN 'Id' THEN [MyTable].[Id]
                        WHEN 'TimeStamp' THEN [MyTable].[TimeStamp]                     
                        WHEN 'StatusCode' THEN [MyTable].[StatusCode]                       

                        ELSE [MyTable].[TimeStamp]
                    END             
            END ASC                 
        ) AS 'Row',
        [MyTable].[Id] AS 'Id',
        [MyTable].[TimeStamp] AS 'TimeStamp',
        [MyTable].[StatusCode] AS 'StatusCode'
    FROM  
        [MyTable]
    WHERE 
        (@Filter_Id is null or [MyTable].[Id] = @Filter_Id) AND     
        (@Filter_StatusCode is null or [MyTable].[StatusCode] = @Filter_StatusCode) AND
        (@Filter_FromTimeStamp IS NULL OR [MyTable].[TimeStamp] >= @Filter_FromTimeStamp) AND
        (@Filter_TillTimeStamp IS NULL OR [MyTable].[TimeStamp] <= @Filter_TillTimeStamp)
    ) AS t1
WHERE 
    Row >=@StartRecord AND 
    Row <= @EndRecord

1 个答案:

答案 0 :(得分:3)

CASE 表达式必须返回特定类型的值。所有THEN条款必须就类型达成一致或允许data type precedence规则确定整体类型并应用转化。

因为你可能不希望例如将所有内容转换为字符串并根据文本排序规则执行排序操作,您需要拆分CASE表达式,这样就不会强制在类型之间进行任何转换。

E.g。

    ORDER BY
        CASE WHEN @SortDirection='Desc' and @SortColumn = 'Id'                        
             THEN [MyTable].[Id]
        END DESC,
        CASE WHEN @SortDirection='Desc' and @SortColumn = 'TimeStamp'                        
             THEN [MyTable].[TimeStamp]
        END DESC,
        CASE WHEN @SortDirection='Desc' and @SortColumn='StatusCode'
             THEN [MyTable].[StatusCode]
        END DESC,
        CASE WHEN @SortDirection='Desc' and @SortColumn not in ('Id','TimeStamp','StatusCode')
            THEN [MyTable].[TimeStamp]
        END DESC,

同样适用于提升种类。