Home Forums SQL Server 7,2000 General replacing multiple characters in a column RE: replacing multiple characters in a column

  • I've got a collection of functions like that that strip out certain characters, html encode data, etc, all based on Jeff Moden's Tally Table concept.

    Try this out for size: it's really fast:

    [font="Courier New"]

        --===== Create and populate the Tally table on the fly

    SELECT TOP 11000 --equates to more than 30 years of dates

                IDENTITY(INT,1,1) AS N

                INTO dbo.Tally

        FROM MASTER.dbo.SysColumns sc1,

                MASTER.dbo.SysColumns sc2

        --===== Add a Primary Key to maximize performance

    ALTER TABLE dbo.Tally

                ADD CONSTRAINT PK_Tally_N

                PRIMARY KEY CLUSTERED (N) WITH FILLFACTOR = 100

    GO

    CREATE FUNCTION StripNonNumeric(@OriginalText VARCHAR(8000))

    RETURNS VARCHAR(8000)

        BEGIN

        DECLARE @CleanedText VARCHAR(8000)

        SELECT @CleanedText = ISNULL(@CleanedText,'') +

            CASE

                --ascii numbers are 48(for '0') thru 57 (for '9')

                        WHEN ASCII(SUBSTRING(@OriginalText,Tally.N,1)) BETWEEN 48

                    AND  57  THEN SUBSTRING(@OriginalText,Tally.N,1)

            ELSE '' END

            FROM dbo.Tally          

            WHERE Tally.N <= LEN(@OriginalText)

        RETURN @CleanedText

        END

    GO

    SELECT dbo.StripNonNumeric('Alex is 25 years old on 01/14/2008')

        --results 2501142008[/font]

    Lowell


    --help us help you! If you post a question, make sure you include a CREATE TABLE... statement and INSERT INTO... statement into that table to give the volunteers here representative data. with your description of the problem, we can provide a tested, verifiable solution to your question! asking the question the right way gets you a tested answer the fastest way possible!