CASE 中的排序依据和不同类型

编程入门 行业动态 更新时间:2024-10-28 14:32:08
本文介绍了CASE 中的排序依据和不同类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要根据参数中的整数输入对结果集进行排序.

I have a requirement to order a result set by a column, based on an Integer input into a parameter.

问题是,我需要为 OrderBy 使用 CASE,而且代码似乎接受 case 列中的第一个TYPE"......任何其他类型都失败.

Problem is, I need to use a CASE for the OrderBy, and it seems the code accepts the first 'TYPE' in the case column... any other types fail.

我的代码是这样的:

WITH error_table AS ( SELECT Row_Number() OVER (ORDER BY CASE @orderBy WHEN 1 THEN received_date -- Last Rx'd message WHEN 2 THEN message_id -- Message Id WHEN 3 THEN zibmat.short_name -- Message action type WHEN 4 THEN error_action.short_name -- Status type WHEN 5 THEN ime.[allocated_date] -- Allocated Date ELSE received_date END) AS RowNumber ,ime.[ijis_message_error_id] ,ime.[message_id] ,ime.[message_version]

因此,当 OrderBy 为 1 时,它会起作用.它按 rx_date 排序...但是当我向它发送 2 时,它因数据时间转换错误而失败.

So, when OrderBy is 1, it works. It sorts by rx_date... but when I sent it a 2, it fails with a data time conversion error.

看起来所有类型都必须相同...

It looks like all the types must be the same...

发送 5 可以正常工作,因为那也是约会时间.

Sending a 5 works fine, as that's a date time too.

有什么办法可以解决这个问题吗?

Is there a way I can fix this?

推荐答案

CASE 语句只能解析为一种数据类型.这与您知道@orderby 只会选择一个分支并且它将是特定数据类型这一事实无关.

A CASE statement must resolve to only one data type. This is regardless of the fact that you know that @orderby will choose only one branch and it will be a particular data type.

你可以使用这样的东西,虽然笨重但可以工作.

You could use something like this, which would be clunky but will work.

ORDER BY CASE @orderBy WHEN 1 THEN received_date -- Last Rx'd message WHEN 2 THEN 0 WHEN 3 THEN 0 WHEN 4 THEN 0 WHEN 5 THEN ime.[allocated_date] -- Allocated Date ELSE received_date END, CASE @orderBy WHEN 1 THEN 0 WHEN 2 THEN message_id -- Message Id WHEN 3 THEN 0 WHEN 4 THEN 0 WHEN 5 THEN 0 ELSE 0 END, CASE @orderBy WHEN 1 THEN '' WHEN 2 THEN '' WHEN 3 THEN zibmat.short_name -- Message action type WHEN 4 THEN error_action.short_name -- Status type WHEN 5 THEN '' ELSE '' END

更多推荐

CASE 中的排序依据和不同类型

本文发布于:2023-11-29 01:12:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644693.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不同类型   CASE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!