SQL Server动态Order By查询,不同数据类型
在SQL Server 2000中,
查询
SELECT DISTINCT A.COLUMN1, B.COLUMN2 FROM TABLEA A, TABLEB B WHERE
A.KEY_ID = B.FK_ID
ORDER BY CASE @ORDER_NAME
WHEN 'COL1' THEN COLUMN1
WHEN 'COL2' THEN COLUMN2
ELSE
COLUMN2
END ASC
我有一个类似于Here A.COLUMN1 is varchar(50) and B.COLUMN2 is datetime的 。当 @ORDER_NAME 的值为“COL2”时,即当 order by 为 datetime 类型时,此查询完美运行,但当我使用“COL1”时,它会给出错误“从字符串转换日期时间时出现语法错误”。
我认为这是因为 SQL Server 试图将所有列转换为日期时间类型。但我找不到替代语法来动态对列进行排序。由于性能问题, EXEC 是不可能的,
我需要提到的是,我试图避免分支,否则上述操作也可以通过 IF ELSE 子句来完成。
In SQL Server 2000
I have a query like
SELECT DISTINCT A.COLUMN1, B.COLUMN2 FROM TABLEA A, TABLEB B WHERE
A.KEY_ID = B.FK_ID
ORDER BY CASE @ORDER_NAME
WHEN 'COL1' THEN COLUMN1
WHEN 'COL2' THEN COLUMN2
ELSE
COLUMN2
END ASC
Here A.COLUMN1 is varchar(50) and B.COLUMN2 is datetime. This query works perfectly when value of @ORDER_NAME is 'COL2' i.e. when order by is of type datetime but when I used 'COL1' it gives error 'Syntax error converting datetime from character string.'
I think that this is because SQL Server is trying to convert all the columns to datetime type. But I can't find an alternative syntax to dynamically sort the columns. EXEC is out of question due to performance issues
I need to mention that I am trying to avoid branching otherwise the above can be done by ane IF ELSE clause also.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有任何数据类型转换问题的版本:
Version without any data type conversion issues:
这应该有效:
This should work:
你可以做类似的事情:
update:
实际上你可以在查询中将日期转换为 varchar 并且它会起作用,我刚刚像上面那样做了,当排序列来自 xquery 表达式时,所以发布它像那样。
You could do something like:
update:
Actually you could probably convert the date to an varchar in you query and it would work, I've just done it like the above before, when the sort columns where coming from an xquery expression so posted it like that.
将它们全部转换为 varchar:
然后您甚至可以按多列排序,当您在按列排序中有许多相似的值时,这很好:
convert them to all to varchar:
you could then even sort by multiple columns then, which is good when you have many similar values in the sort by column: