简体   繁体   English

如何在sql server中获取max length的值

[英]How to get the value of max length in sql server

i would like to ask you if there is a way to get the value of maxlength of column in ms sql server. 我想问你是否有办法在ms sql server中获取列的maxlength值。
For example in the table A we have: 例如,在表A中我们有:

id  | value
----+--------
 1  | 0123
 2  | 00034567
 3  | 547

The desired result for this data set is 00034567. 该数据集的期望结果是00034567。

Wherever i have searched for this problem i get the answer select max(len(value)) which is not what i need, because it gives the max number of characters of the value and not the value itself. 无论我在哪里搜索这个问题,我都会得到答案选择max(len(value)),这不是我需要的,因为它给出了值的最大字符数而不是值本身。

Any ideas? 有任何想法吗?

SELECT TOP 1 t.value
FROM table AS t
ORDER BY LEN(t.value) DESC

你使用的sql是正确的,你只需要将它转换为nvarchar

Sort by length and take the first row: 按长度排序并占据第一行:

select top 1 value
from mytable
order by len(value) desc

If you want ties: 如果你想要联系:

select value
from mytable
where len(value) = (select max(len(value)) from mytable)

Or more efficient but SQL Server specific: 或者更高效但SQL Server特定:

select value from (
  select value,
  rank() over (order by len(value) desc) rank
  from mytable) x
where rank = 1

See SQLFiddle for last one. 请参阅SQLFiddle以获取最后一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM