Domanda

Dato il seguente codice:

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;
.

Io ottengo un risultato come questo:

FirstVal    LastVal    SeqIncrement 
-------     -------    -------------- 
38          50         2
.

Vorrei avere un modo Set Based per scattare questi risultati e inserire ciascun valore (saltando da seqincrement) in questa tabella:

DECLARE @newIds TABLE (IdType VARCHAR(100), [NewId] BIGINT)
.

Quindi quando ho finito, un SELECT * from @newIds tornerebbe:

IdType    NewId
-------   -------
TestId    38
TestId    40
TestId    42
TestId    44
TestId    46
TestId    48
TestId    50
.

Nota: non voglio usare un loop se possibile.Inoltre, dovrò ottenere una quantità variabile di risultati (questo mostra 7, ma cambierà ogni chiamata).

Penso che ci sia una croce applicata o qualche cosa che può farlo.Ma non riesco a capirlo.

È stato utile?

Soluzione

Questo dovrebbe essere buono fino a circa 2.500 valori (a seconda della versione):

;WITH x(n) AS 
(
  SELECT TOP (@variableNumberOfIdsNeeded)
    (ROW_NUMBER() OVER (ORDER BY number)-1) 
    * CONVERT(BIGINT, @SeqIncr)
    + CONVERT(BIGINT, @FirstSeqNum)
  FROM master.dbo.spt_values
  ORDER BY number
)
--INSERT @newIds([NewId]) 
SELECT n FROM x;
.

Se hai bisogno di più o sono preoccupati di utilizzare la vista master.dbo.spt_values, consultare altre tecniche possibili per generare set senza loop qui:

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a dba.stackexchange
scroll top