how to find max(varchar field) using sql server

  • Hi,

    I am using SQL Server , I have a field name bookid of type varchar.

    Example data for this field is given below:

    BK1

    BK2

    BK10

    BK11

    I am using select substring(max(bookid),3,8)) from tablename to get the max value of Bookid field.

    But, the result is : BK2.

    Please help me in resolving this issue. I cannot change the datatype of the bookid. Give me a perfect query to get the max value of that varchar field.

    Thanks.

  • SELECT MAX(CAST(SUBSTRING(bookid,3, LEN(bookid)) AS INT)) from tablename

  • You can skip the len(bookid) part by lion

    SELECT MAX(convert(INT,SUBSTRING(bookid,3,8))) FROM tablename

  • Its better not to script the LEN part . It is there in case the length of the bookid varies. The length of bookid could be less than or greater than 8. Skip that only if the length is fixed as 8.

    "Keep Trying"

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply