prova questo:
create table #smalltable (id int, [begin] int, [end] int)
insert into #smalltable values (123,1,4)
insert into #smalltable values (124,1,12)
insert into #smalltable values (125,1,7)
;WITH digits (d) AS (
SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION
SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION
SELECT 7 UNION SELECT 8 UNION SELECT 9 UNION
SELECT 0)
SELECT
s.id, s.[begin], n.Number AS [End]
FROM (SELECT i.d + ii.d * 10 + iii.d * 100 + iv.d * 1000 +
v.d * 10000 + vi.d * 100000 AS Number
FROM digits i
CROSS JOIN digits ii
CROSS JOIN digits iii
CROSS JOIN digits iv
CROSS JOIN digits v
CROSS JOIN digits vi
) AS N
INNER JOIN #smalltable s ON 1=1
INNER JOIN (SELECT MAX([end]) AS MaxEnd FROM #smalltable) dt ON 1=1
WHERE n.Number > 0 AND n.Number<=dt.MaxEnd
AND n.Number<=s.[end]
ORDER BY s.id,n.Number
commenti
- non nominare le tue colonne con le parole riservate:"inizio" e "fine", un giorno mi ringrazierai.
- se prevedi di eseguirlo in produzione molte volte, crea una tabella di numeri
e usa invece questa query:
devi avere una tabella Numeri prima che funzioni (vedi link sopra)
SELECT
s.id,s.[begin],n.Number AS [End]
FROM Numbers n
INNER JOIN #smalltable s ON 1=1
WHERE n.Number > 0 AND n.Number<=s.[end]
ORDER BY s.id,number
funzionerà meglio.