inserting GL001 to GL100 in a loop

  • How to insert the values GL001 to GL100 to a table.

    i can write the loop like

    declare @id int

    set @id = 001

    While @id <=100

    begin

    insert myTable(Activity_Codes)

    select 'GL'+convert(varchar, @id)

    set @id=@id+1

    end

    but my concern is how to append an additional 00 to 1 so it'll be 001

    and a 0 to 21 so that it'll be 021, etc....

    Thanks,

    KB

    Thanks,
    Santhosh


    Human Knowledge Belongs To The World !!

  • Try this

    declare @id int

    set @id = 001

    While @id <=100

    begin

    insert myTable(Activity_Codes)

    select 'GL'+ Right('000' + convert(varchar, @id),3)

    set @id=@id+1

    end

  • vstitte (2/1/2010)


    Try this

    declare @id int

    set @id = 001

    While @id <=100

    begin

    insert myTable(Activity_Codes)

    select 'GL'+ Right('000' + convert(varchar, @id),3)

    set @id=@id+1

    end

    Yes, got it...

    Thanks,

    KB

    Thanks,
    Santhosh


    Human Knowledge Belongs To The World !!

  • You are welcome.

  • Get out of the habit of looping , use tally tables

    This ...

    insert myTable(Activity_Codes)

    select 'GL'+ Right('000' + convert(varchar(3), number),3) from master..spt_values where type = 'P' and number between 1 and 100

    Is preferable



    Clear Sky SQL
    My Blog[/url]

  • Thanks Dave.

    Awesome. I am going to start thinking Tally going forward. Really cool.

  • Dave Ballantyne (2/1/2010)


    Get out of the habit of looping , use tally tables

    This ...

    insert myTable(Activity_Codes)

    select 'GL'+ Right('000' + convert(varchar(3), number),3) from master..spt_values where type = 'P' and number between 1 and 100

    Is preferable

    Wow... !!!

    Thanks,
    Santhosh


    Human Knowledge Belongs To The World !!

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

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