looping through a string

  • how can i loop through a string '123456'

    and add +1 to each number so result will be '234567'

    thanks

  • The following non-ANSI t-sql should do it:

    DECLARE @a char(6)

        ,@b varchar(6)

    SET @a = '123456'

    SET @b-2 = ''

    SELECT @b-2 = @b-2 + D.Number

    FROM (

            SELECT CAST (

                        CASE D1.Number

                        WHEN 9 THEN 0

                        ELSE D1.Number + 1

                        END

                        AS char(1)

                    )

            FROM (

                    SELECT CAST(SUBSTRING(@a, D2.Number, 1) AS tinyint)

                    FROM (

                            SELECT 1 UNION ALL

                            SELECT 2 UNION ALL

                            SELECT 3 UNION ALL

                            SELECT 4 UNION ALL

                            SELECT 5 UNION ALL

                            SELECT 6

                        ) D2 (Number) -- or use number table

                ) D1 (Number)

        ) D (Number)

    SELECT @b-2

     

Viewing 2 posts - 1 through 1 (of 1 total)

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