Given the following code:
CREATE SEQUENCE dbo.NextTestId AS [bigint]
START WITH 10 INCREMENT BY 2 NO CACHE
GO
DECLARE
@variableNumberOfIdsNeeded INT = 7, -- This will change for each call
@FirstSeqNum SQL_VARIANT , @LastSeqNum sql_variant, @SeqIncr sql_variant;
EXEC sys.sp_sequence_get_range @sequence_name = N'dbo.NextTestId',
@range_size = @variableNumberOfIdsNeeded,
@range_first_value = @FirstSeqNum OUTPUT,
@range_last_value = @LastSeqNum OUTPUT,
@sequence_increment = @SeqIncr OUTPUT;
-- The following statement returns the output values
SELECT @FirstSeqNum AS FirstVal, @LastSeqNum AS LastVal, @SeqIncr AS SeqIncrement;
I get a result like this:
FirstVal LastVal SeqIncrement
------- ------- --------------
38 50 2
I would like to have a set based way to take these results and insert each value (skipping by SeqIncrement) into this table:
DECLARE @newIds TABLE (IdType VARCHAR(100), [NewId] BIGINT)
So when I am done, a SELECT * from @newIds would return:
IdType NewId
------- -------
TestId 38
TestId 40
TestId 42
TestId 44
TestId 46
TestId 48
TestId 50
NOTE: I don't want to use a loop if possible. Also, I will need to get a variable amount of results (this one shows 7, but it will change each call).
I think there may be a cross apply or some such thing that can do this. But I can't seem to figure it.