Home Forums SQL Server 2008 SQL Server Newbies how to trim away the first 'x' and last 'y number of characters from a string RE: how to trim away the first 'x' and last 'y number of characters from a string

  • Another way. And this will work for multiple trailing numbers or when there aren't any.

    DECLARE @strings TABLE (LoginID VARCHAR(100))

    INSERT INTO @strings

    VALUES ('adventure-works\peter0'), ('Northwind\mary009'), ('Test\mark');

    SELECT SUBSTRING(p, 1, ISNULL(NULLIF(PATINDEX('%[0-9]%',p),0),8000)-1)

    FROM

    (

    SELECT p = SUBSTRING(LoginID,CHARINDEX('\', LoginID)+1,8000) FROM @strings

    ) prep;

    "I cant stress enough the importance of switching from a sequential files mindset to set-based thinking. After you make the switch, you can spend your time tuning and optimizing your queries instead of maintaining lengthy, poor-performing code."

    -- Itzik Ben-Gan 2001