how to loop string in sql

  • I need to create a dynamic string, one that loops to pick up values and add them to itself.

    The below code should produce:

    "anythinganythinganythinganythinganythinganythinganything"

    but it doesn't.

    How can i make it do this?

    declare @sqlReturn as varchar(500)

    declare @N_int as int

    SET @N_int = 0

    While (@N_int <= 7)

    BEGIN

    select @sqlReturn = @sqlReturn + 'anything'

    SET @N_int = @N_int + 1

    END

    print @sqlReturn

  • Hi,

    You just forgot to initialize your variable.

    declare @sqlReturn as varchar(500)

    declare @N_int as int

    --Initialize your variable, otherwise @sqlReturn=null

    set @sqlReturn=''

    SET @N_int = 0

    While (@N_int <= 7)

    BEGIN

    select @sqlReturn = @sqlReturn + 'anything'

    SET @N_int = @N_int + 1

    END

    select @sqlReturn

    Regards,

    Ahmed

  • Your variable starts as NULL and I think that 'anything' concatenated with NULL yields NULL, so giving the variable an initial value should fix that. I think there's also a setting that changes that behavior but I can't remember the name off the top of my head. (It's probably something like 'CONCAT_NULL_YIELD_NULL')


    And then again, I might be wrong ...
    David Webb

  • Man, I have got to learn to type faster....


    And then again, I might be wrong ...
    David Webb

  • Hi,

    Thanks David for the info

    SET CONCAT_NULL_YIELDS_NULL off

    your code

    SET CONCAT_NULL_YIELDS_NULL on

    Regards,

    Ahmed

  • ahh gees thanks guys I knew I left something stupid out.

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

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