SUPERCAT.DEV

Benvenut* sul mio blog

TSQL

Ciclo in TSQL

26-10-2023

Eseguire un ciclo sui valori di una tabella

DECLARE @T TABLE (
	ID INT,
	NOME VARCHAR(20)
)

CREATE TABLE #T_ID (
	RowID int IDENTITY, 
	ID INT
)

INSERT INTO @T (ID, NOME) VALUES 
	(100, 'ANTONELLA'),
	(200, 'ALBERTA'),
	(300, 'ANDREA'),
	(400, 'BEATRICE'),
	(500, 'BOLOGNA'),
	(600, 'BARI')

INSERT INTO #T_ID
SELECT ID FROM @T WHERE NOME LIKE 'AN%'

DECLARE @NumberRecords int, @RowCounter int
SELECT @NumberRecords = COUNT(*) FROM #T_ID
SET @RowCounter = 1

WHILE @RowCounter <= @NumberRecords
BEGIN
	DECLARE @ID_CURRENT INT
	SELECT @ID_CURRENT = ID FROM #T_ID WHERE RowID = @RowCounter
	
	SELECT NOME FROM @T WHERE ID = @ID_CURRENT

	SET @RowCounter = @RowCounter + 1
END