SQL Rownumber() Order By 子句中的 Case 语句不适用于 varchar 和 int 值
为什么这不起作用?
DECLARE @temp table
(ShipNo int,
Supplier varchar(10)
)
INSERT INTO @temp VALUES (1,'CFA')
INSERT INTO @temp VALUES (1, 'TFA')
INSERT INTO @temp VALUES (2, 'LRA')
INSERT INTO @temp VALUES (2, 'LRB')
INSERT INTO @temp VALUES (3, 'ABC')
INSERT INTO @temp VALUES (4, 'TFA')
Declare @OrderBy varchar(255)
sET @OrderBy = 'Supplier'
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
WHEN 'ShipNo' THEN ShipNo
END
) AS RowNo,
ShipNo,
Supplier
FROM @temp
但是,如果您在 Case 语句中将 ShipNo 转换为 varchar,它是否有效?
Why doesn't this work?
DECLARE @temp table
(ShipNo int,
Supplier varchar(10)
)
INSERT INTO @temp VALUES (1,'CFA')
INSERT INTO @temp VALUES (1, 'TFA')
INSERT INTO @temp VALUES (2, 'LRA')
INSERT INTO @temp VALUES (2, 'LRB')
INSERT INTO @temp VALUES (3, 'ABC')
INSERT INTO @temp VALUES (4, 'TFA')
Declare @OrderBy varchar(255)
sET @OrderBy = 'Supplier'
SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
WHEN 'Supplier' THEN Supplier
WHEN 'ShipNo' THEN ShipNo
END
) AS RowNo,
ShipNo,
Supplier
FROM @temp
But if you cast the ShipNo to a varchar in the Case statement it DOES work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我知道这是旧帖子,但这适用于任何遇到此问题并正在寻找解决方案的人:
基本上,您将每个字段放在自己的情况下。 出现转换失败等错误时,才执行此操作。
仅当两列的数据类型或字段内值不同时,或者在尝试将 int 转换为 varchar 或 varchar 转换为 int 时
I am aware that this is old post but this is for any one who tumbles upon this issue and is looking for a solution:
basically you are putting each field in its own case. Do this only when their data type or value inside field differs for both the columns or when you are getting error such as
conversion failed when trying to convert int to varchar or varchar to int..
来自联机丛书:
“else_result_expression 和任何 result_expression 的数据类型必须相同或者必须是隐式转换。”
因此Supplier 和ShipNo 必须是相同的数据类型。
From Books Online:
"The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion."
So Supplier and ShipNo must be the same datatype.