Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi,I have a table with the following dataID StartYear EndYear1 2006 2008I need to write some SQL that will output this as rows of data like the followingID Year1 20061 20071 2008Can anyone help with writing a query to perform this.Thanks,Gavin,
PeterNeo
Constraint Violating Yak Guru
357 Posts
Posted - 2008-11-05 : 04:08:04
U need a Tally or Numbers table to do it.
DECLARE @T TABLE (ID INT, StartYear INT, EndYear INT)INSERT INTO @TSELECT 1, 2006, 2008SELECT T.Id, M.Number AS 'Year'FROM @T TINNER JOIN Master..spt_Values M ON M.Number BETWEEN T.StartYear AND T.EndYearWHERE M.Type = 'P'
"There is only one difference between a dream and an aim. A dream requires soundless sleep to see, whereas an aim requires sleepless efforts to achieve..!!"
madhivanan
Premature Yak Congratulator
22864 Posts
Posted - 2008-11-05 : 04:14:31
[code]declare @t table(ID int,StartYear int,EndYear int)insert into @tselect 1 ,2006 ,2008select t1.id,t2.number from @t as t1 inner join( select row_number() over(order by s1.name) as number from sysobjects s1 cross join sysobjects as s2) as t2 on t2.number between t1.StartYear and t1.EndYear[/code]Also look for UNPIVOT in sql server help fileMadhivananFailing to plan is Planning to fail