我收到了错误:
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
答案 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,
同样适用于提升种类。