Results 1 to 3 of 3

Thread: MAX for varchar or character expresions or strings

  1. #1
    Join Date
    Jul 2003
    Location
    dallas,tx
    Posts
    1

    MAX for varchar or character expresions or strings

    Say i have a COLUMN name varchar(20)

    NAME:
    ----
    john
    john/a
    john/b
    john/a/a

    ------

    I want to find the LONGEST NAME in the column and I am trying to use

    : Select MAX(name) from tablename

    SQL 2000 gives the max as per alphabetical order and in the above example the MAX is john/b

    IS there any direct SQL statement to get the MAX name where MAX refers to the LONGEST in terms of length .


    I have been able to do it with 2 sql statements where i first find the longest length and then give a query where i match the length..But is there any simpler way??

  2. #2
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    use tempdb

    create table x1 (name varchar(100))
    insert into x1 select 'john'
    insert into x1 select 'john/a'
    insert into x1 select 'john/b'
    insert into x1 select 'john/a/a'


    select * from x1 where len(name) = (select max(len(name)) from x1)

    or

    select top 1 name, max(len(name)) from x1 group by name order by len(name) desc

    or

    select name from (
    select top 1 name, max(len(name)) as len from x1 group by name order by len(name) desc) as x

  3. #3
    Join Date
    Sep 2002
    Location
    Fantasy
    Posts
    4,254
    select top 1 name from x1 order by len(name) desc

    or
    select top 1 name from x1 order by datalength(name) desc


    this would be your best bet

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •