To pass a table into the stored procedure use table-valued parameter.
At first create a type:
CREATE TYPE [dbo].[ProductsTableType] AS TABLE(
[ID] [varchar](50) NOT NULL,
[qty] [int] NOT NULL
)
Then use this type in the stored procedure. The @ParamProducts
is a table and can be used in all queries where a table can be used.
CREATE PROCEDURE [dbo].[AddProducts]
@ParamProducts ProductsTableType READONLY
AS
BEGIN
...
END
To actually insert required number of rows I would use a table of numbers , http://web.archive.org/web/20150411042510/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html
In my database I have a table called Numbers
with a column Number
that contains numbers from 1 to 100,000. Once you have such table it is trivial to get the set that you need.
DECLARE @T TABLE (ID varchar(50), qty int);
INSERT INTO @T (ID, qty) VALUES ('productA', 4);
INSERT INTO @T (ID, qty) VALUES ('productB', 1);
INSERT INTO @T (ID, qty) VALUES ('productV', 9);
SELECT *
FROM
@T AS Products
INNER JOIN dbo.Numbers ON Products.qty >= dbo.Numbers.Number
;
Result set
ID qty Number
productA 4 1
productA 4 2
productA 4 3
productA 4 4
productB 1 1
productV 9 1
productV 9 2
productV 9 3
productV 9 4
productV 9 5
productV 9 6
productV 9 7
productV 9 8
productV 9 9
This is an example. In your case you would have this SELECT
inside INSERT INTO YourFinalTable
.
Quantity
column rather than trying to group rows whenever a count is needed.