Let’s supposed I Have a table with products like this
product | number
----------------------
aaaa | 2
bbbb | 3
cccc | 1
dddd | 4
It’s a little more complex, but the idea is the same.
I need to return something like this
aaaa0001
aaaa0002
bbbb0003
bbbb0004
bbbb0005
cccc0006
dddd0007
dddd0008
dddd0009
dddd0010
I mean, each product the number of times specified in the column, with some kind of identificator at the end.
How can I do this ?
I thought of table variable, with identity on the Id
DECLARE @Codigos TABLE (ID INT IDENTITY(1,1), Barra Varchar(50) NOT NULL)
and after the inserts, do
select rtrim(ltrim(barra)) + right('0000' + rtrim(ltrim(cast(id as varchar(10)))),4) from @Codigos
but This mean that I’ll have to insert for each products the number of times in the product variable, like
@Codigos
id | Barra
----------------
1 | aaaa
2 | aaaa
and I’m facing problems with that. How can I do that ? With a cursor ? That’s what I thought, but I want to know if there’s a better option.
Maximum will be 300 rows in original table.
This should do it:
Here is a sqlfiddle for you to try.