behaviour of LEN()

  • Hi,

    in SQL Server i have tried the below query:

    SELECT LEN('1 ')

    it returns 1.

    I want the length which includes the spaces. i.e 3.

    Is there any other function available for this?

    Thanks.

    Thanks,
    Pandeeswaran

  • As clearly documented in Books Online:

    Returns the number of characters of the specified string expression, excluding trailing blanks.

    Note:

    To return the number of bytes used to represent an expression, use the DATALENGTH function.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • This is also true for binary values, since LEN seem to convert them to varchar.

    See http://weblogs.sqlteam.com/peterl/archive/2008/07/22/Why-LEN-differs-from-DATALENGTH-when-using-BINARY-data.aspx


    N 56°04'39.16"
    E 12°55'05.25"

  • If you determined to use LEN function and want it to return 3 in your case you can do the following:

    select len('1 ' + 'a') - 1

    :w00t::w00t::w00t:

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]

  • or

    SELECT LEN(REVERSE('1 ')) 😛

  • nigel. (8/2/2011)


    or

    SELECT LEN(REVERSE('1 ')) 😛

    I wanted to put this first, but it has limitation: will not work for string with trailing spaces :hehe:

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]

  • Eugene Elutin (8/2/2011)


    nigel. (8/2/2011)


    or

    SELECT LEN(REVERSE('1 ')) 😛

    I wanted to put this first, but it has limitation: will not work for string with trailing spaces :hehe:

    Ah! Good point

  • You can also do this:

    SELECT LEN(REPLACE('1 ',' ','A'))

  • The following pattern can be useful when you can't be sure whether the input string is Unicode or not:

    DECLARE @string VARCHAR(100) = ''

    DECLARE @string2 NVARCHAR(100) = N''

    SELECT DATALENGTH(@string) / ISNULL(NULLIF(DATALENGTH(LEFT(@string, 1)), 0), 1)

    SELECT DATALENGTH(@string2) / ISNULL(NULLIF(DATALENGTH(LEFT(@string2, 1)), 0), 1)

Viewing 9 posts - 1 through 8 (of 8 total)

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