How to get max length value in sql server

I would like to ask you if there is a way to get the maxlength value of a column in ms sql server.
For example, in table A we have:

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

      

The desired output for this dataset is 00034567.

Wherever I look for this problem, I get a select max (len (value)) response, which I don't need because it gives the maximum number of characters of the value, not the value itself.

Any ideas?

+3


source to share


3 answers


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

      



+3


source


sql you are using is correct, you just need to send it to nvarchar



0


source


Sort by length and take the first line:

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

      

If you need connections:

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

      

Or more efficient than SQL Server:

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

      

See SQLFiddle for the latter.

0


source







All Articles