访问 ORDER BY 子句中的直接列值
我刚刚在某些代码中发现了一个错误。有一个类似这样的 SQL:
SELECT convert(varchar(11),COL1,106) as COL1
FROM TAB
ORDER BY COL1 DESC
现在,返回的 COL1 值格式如下所示:
17 Sep 2001
07 Mar 2011
数据库中存储的值如下所示:
2011-03-07 00:00:00
2001-09-17 00:00:00
但由于 ORDER BY 子句使用
17 Sep 2001
07 Mar 2011
值,因此排序不正确。由于我无法更改列名称(查询和使用它的应用程序之间存在很大的依赖性),因此我必须修改 &修复 SQL 语句以返回具有正确排序的行。有没有办法以 ORDER BY 子句使用存储在行列中的实际值而不是转换后的值的方式对其进行修改?我尝试过:
ORDER BY TAB.COL1 DESC
但也没有成功。
谢谢,帕维尔
I've just spotted a bug in some piece of code. There is an SQL similar to this:
SELECT convert(varchar(11),COL1,106) as COL1
FROM TAB
ORDER BY COL1 DESC
Now, COL1 value format returned looks like this:
17 Sep 2001
07 Mar 2011
and values stored in database look like this:
2011-03-07 00:00:00
2001-09-17 00:00:00
But because ORDER BY clause uses
17 Sep 2001
07 Mar 2011
values, ordering is incorrect. As I cannot change column names (there's large dependency between query and application that uses it), I have to modify & fix the SQL statement to return rows with correct ordering. Is there any way to modify it in a way that ORDER BY clause uses real value stored in row's column instead of converted one? I tried :
ORDER BY TAB.COL1 DESC
but it also didn't work.
Thanks,Pawel
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以将字段的别名更改为
COL1
以外的名称,这应该会导致 ORDER BY 出现在字段本身上,而不是计算出的别名上:UPDATE
如果列名需要保持不变试试这个:
You could just change the alias name of your field to something other than
COL1
, that should cause the ORDER BY to go on the field itself and not the computed alias:UPDATE
If the column name needs to stay the same try this:
您应该使用表名来限定您的列名
尝试此
在 SQL Server 2008 和 SQL Server 2005 上
结果:这不适用于 SQL Server 2000,因此如果您确实需要列名与别名相同,这里有一个解决方法。
编辑
如果您具有 SQL Server 2000(80) 兼容级别,它也无法在 SQL Server 更高版本中运行。在这种情况下,我建议您更改兼容性级别。
You should qualify your column name with table name
Try this
Result on SQL Server 2008 and SQL Server 2005:
This does not work for SQL Server 2000 so here is a workaround for that if you really need the column name to be the same as the alias.
Edit
It will also not work in version later that SQL Server if you have Compatibility Level SQL Server 2000(80). In that case I suggest you change compatibility level.
如果您想在转换值之前进行排序,请尝试以下操作:
或者如果您想在转换值之后进行排序,请尝试以下操作:
if you want sorting before converting value then try this :
or if you want sorting after converting value then try this :
您可以尝试这样的操作:
这基本上会在将结果放入转换方法之前对结果进行排序。
You can try something like this:
This will basically order the result before throwing it into the convert method.
双重重命名:
Double renaming: