quizas esto te sirva:
Código SQL:
Ver originalCREATE TABLE #temp
(
inicial datetime,
final datetime,
dia1 INT,
)
INSERT INTO #temp VALUES (getdate(),dateadd(dd,2,getdate()))
INSERT INTO #temp VALUES ('06/01/2013','06/15/2013')
DECLARE @total INT
DECLARE @x INT
DECLARE @query Nvarchar(MAX)
SELECT @total=MAX(datediff(dd,inicial,final)) FROM #temp
SELECT *,IDENTITY(INT,1,1) AS rn INTO #temp2 FROM #temp
SET @x=1
SET @query='create table ##valores(inicial datetime,final datetime,'
while @x<=@total
BEGIN
IF @x=@total
BEGIN
SET @query=@query + 'Dia' + CONVERT(VARCHAR(20),@x) + ' varchar(20))'
END
ELSE
SET @query=@query + 'Dia' + CONVERT(VARCHAR(20),@x) + ' varchar(20),'
SET @x=@x+1
END
print @query
EXEC sp_executesql @query
SELECT @total=COUNT(*) FROM #temp2
SET @x=1
SET @query=''
DECLARE @y INT
DECLARE @query2 AS Nvarchar(MAX)
while @x<=@total
BEGIN
SET @y=1
SET @query='insert into ##valores (inicial,final,'
SET @query2='select inicial,final,'
while @y<=(SELECT datediff(dd,inicial,final) FROM #temp2 WHERE rn=@x)
BEGIN
IF @y=(SELECT datediff(dd,inicial,final) FROM #temp2 WHERE rn=@x)
BEGIN
SET @query=@query + 'dia' + CONVERT(VARCHAR(20),@y) + ')'
SET @query2=@query2 + CHAR(39) + '*' + CHAR(39) + ' from #temp2 where rn=' + CONVERT(VARCHAR(20),@x)
END
ELSE
BEGIN
SET @query=@query + 'dia' + CONVERT(VARCHAR(20),@y) + ','
SET @query2=@query2 + CHAR(39) + '*' + CHAR(39) + ','
END
SET @y=@y+1
END
print @query
print @query2
SET @query=@query + ' ' + @query2
EXEC sp_sqlexec @query
SET @x=@x+1
END
SELECT * FROM ##valores
DROP TABLE #temp2
DROP TABLE ##valores
saludos!