Count number of leading character

  • Hello all.

    I need a query that will give me the number of leading spaces in a string. For instance in this string ' =10 02=5608= ' i need to know how many spaces are in the front of it. Since there are spaces in the string in the middle and the end i cannot use count since it will give me the number of all the spaces.

    Thank you for your help

  • DECLARE @s-2 VARCHAR(20)

    SET @s-2 = ' =10 02=5608= '

    SELECT LEN(@s) - LEN(LTRIM(@s))

    ____________________________________________________

    Deja View - The strange feeling that somewhere, sometime you've optimised this query before

    How to get the best help on a forum

    http://www.sqlservercentral.com/articles/Best+Practices/61537
  • This may seem rather simplistic but you could try D-ECLARE @String char(17)

    SET @String = ' =10 02=5608= '

    SELECT LEN(@String) - LEN(LTRIM(@String))Perhaps create a simple scalar function to return it for you?

    ______________________________________________________________________________Never argue with an idiot; Theyll drag you down to their level and beat you with experience

  • Mark-101232 (9/9/2013)


    DECLARE @s-2 VARCHAR(20)

    SET @s-2 = ' =10 02=5608= '

    SELECT LEN(@s) - LEN(LTRIM(@s))

    Thank you Mark. Its funny because i used that in a previous iteration of my code and didnt think of using the LTRIM with it. Appreciate it!! 🙂

  • Another option is

    SELECT PATINDEX('%[^ ]%',@s) - 1

    Not sure if it'll be any quicker, but you could add in tabs into the pattern as well

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

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