SQL Rownumber() Order By 子句中的 Case 语句不适用于 varchar 和 int 值

发布于 2024-07-07 18:38:52 字数 581 浏览 12 评论 0原文

为什么这不起作用?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

叹梦 2024-07-14 18:38:52

我知道这是旧帖子,但这适用于任何遇到此问题并正在寻找解决方案的人:

SELECT ROW_NUMBER() OVER (ORDER BY  
CASE @OrderBy 
 WHEN 'Supplier' THEN Supplier
END
CASE @OrderBy
 WHEN 'ShipNo' THEN ShipNo 
END 
)

基本上,您将每个字段放在自己的情况下。 出现转换失败等错误时,才执行此操作。

仅当两列的数据类型或字段内值不同时,或者在尝试将 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:

SELECT ROW_NUMBER() OVER (ORDER BY  
CASE @OrderBy 
 WHEN 'Supplier' THEN Supplier
END
CASE @OrderBy
 WHEN 'ShipNo' THEN ShipNo 
END 
)

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..

挽清梦 2024-07-14 18:38:52

来自联机丛书:

CASE
WHEN Boolean_expression THEN result_expression 
    [ ...n ] 
[ 
    ELSE else_result_expression 
] 
END

“else_result_expression 和任何 result_expression 的数据类型必须相同或者必须是隐式转换。”

因此Supplier 和ShipNo 必须是相同的数据类型。

From Books Online:

CASE
WHEN Boolean_expression THEN result_expression 
    [ ...n ] 
[ 
    ELSE else_result_expression 
] 
END

"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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文