So it’s my understanding that looping and cursors should be avoided unless absolutely necessary. In my situation it seems to me that if I have to rely on them I am doing it wrong so I’d like the communities input.
I am writing a stored procedure to add items to a queue, the number of items added are dependent on the intervals setup for the item type. Once the data is inserted into the queue I need to add the ID’s of the queue items to other tables. I am running into an issue here as I generally rely on SCOPE_IDENTITY() to pull the ID for return.
Below is my table structure:
CREATE TABLE QueueItem (
QueueItemID [int] IDENTITY NOT NULL,
ReferenceID [int] NOT NULL,
StartDate [datetime] NOT NULL
);
CREATE TABLE CatalogDate (
ReferenceID [int] NOT NULL,
CatalogID [int] NOT NULL,
DayCount [int] NOT NULL
);
CREATE TABLE ItemInterval (
ReferenceID [int] NOT NULL,
Interval [int] NOT NULL
);
CREATE PROCEDURE SetQueueItem
@ReferenceID [int],
@UserID [int]
AS
BEGIN
DECLARE @DayCount [int]
DECLARE @CatalogID [int]
DECLARE @QueueItemID [int]
SELECT @DayCount = DayCount, @CatalogID = CatalogID
FROM CatalogDate
WHERE ReferenceID = @ReferenceID
DECLARE @Date [datetime] = --SELECT Date from another table using @UserID and @CatalogID
DECLARE @StartDate [datetime] = (SELECT DATEADD(dd, @DayCount, @Date))
INSERT INTO QueueItem(ReferenceID, StartDate)
SELECT @ReferenceID, DATEADD(@DateCount-Interval), @Date)
FROM ItemInterval
WHERE ReferenceID = @ReferenceID --SELECT RETURNS MULTIPLE ROWS
Now once the insert of multiple records has been done I need to take the QueueItemID‘s that were generated from the inserts and insert them along with some additional data in two other tables.
The only ways I can see of accomplishing this is by either breaking up the INSERT to loop through each record in ItemInterval and insert them one at a time, or to query the MAX records from the QueueItem table before and after the insert and then loop through the difference assuming the ID’s are perfectly sequential.
Thoughts?
Thanks to @StarShip3000 for the references on
OUTPUTTo solve this problem I dumped the results into a variable table using
OUTPUTand then use that table to insert the results in the other tables.Viola!