Estimados,
Estuve "trabajando" (copie, pegue un trabaje un poco...) en esta consulta:
Código SQL:
Ver originalDECLARE @A INT, @YearsPVT NVARCHAR(MAX)
DECLARE @Desde NVARCHAR(50), @Hasta NVARCHAR(50)
SET @Desde=N'2014-09-01'
SET @Hasta=N'2014-09-03'
DECLARE @TableYears AS TABLE([A] INT NOT NULL)
INSERT INTO @TableYears SELECT DISTINCT DAY(fecdoc) AS [A] FROM tve WHERE fecdoc BETWEEN @Desde AND @Hasta
SET @A=(SELECT MIN([A]) FROM @TableYears)
SET @YearsPVT=N''
WHILE @A IS NOT NULL
BEGIN
SET @YearsPVT=@YearsPVT+N',['+CONVERT(NVARCHAR(10),@A)+N']'
SET @A=(SELECT MIN([A]) FROM @TableYears WHERE [A]>@A)
END
SET @YearsPVT=SUBSTRING(@YearsPVT,2,LEN(@YearsPVT))
PRINT @YearsPVT
DECLARE @SQL NVARCHAR(MAX)
DECLARE @WHERE NVARCHAR(MAX)
SET @WHERE=N'
SET @SQL= N'SELECT *
FROM (
SELECT tve.idbodega,bodegas.bodega, DAY(fecdoc) [A] ,total FROM tve
INNER JOIN bodegas ON tve.idbodega=bodegas.idbodega
[U][B]WHERE fecdoc BETWEEN "2014-09-01" AND "2014-09-03" AND tve.idbodega="7"[/B][/U]
) pvt
PIVOT (SUM(total) FOR [A] IN ('+@YearsPVT+')) AS Child
ORDER BY idbodega'
EXECUTE sp_executesql @SQL
El codigo en negrita, en realidad me gustaria completarlo con variables PHP.
Esta consulta echa directo en la base de datos FUNCIONA.
cuando la guardo en una variable de PHP y la llamo....:
Código PHP:
Ver original$TxtConsulta="DECLARE @A INT, @YearsPVT NVARCHAR(MAX)
DECLARE @TableYears AS TABLE([A] INT NOT NULL)
INSERT INTO @TableYears SELECT DISTINCT DAY(fecdoc) as [A] FROM tve where fecdoc between '$fecha_desde_epos' and '$fecha_hasta_epos'
SET @A=(SELECT MIN([A]) FROM @TableYears)
SET @YearsPVT=N''
WHILE @A IS NOT NULL
BEGIN
SET @YearsPVT=@YearsPVT+N',['+CONVERT(NVARCHAR(10),@A)+N']'
SET @A=(SELECT MIN([A]) FROM @TableYears WHERE [A]>@A)
END
SET @YearsPVT=SUBSTRING(@YearsPVT,2,LEN(@YearsPVT))
PRINT @YearsPVT
DECLARE @SQL NVARCHAR(MAX)
SET @SQL=N'SELECT *
FROM (
SELECT tve.idbodega,bodegas.bodega, DAY(fecdoc) [A] ,total FROM tve
inner join bodegas on tve.idbodega=bodegas.idbodega
where fecdoc between \"$fecha_desde_epos\" and \"$fecha_hasta_epos\"
) pvt
PIVOT (SUM(total) FOR [A] IN ('+@YearsPVT+')) AS Child
ORDER by idbodega'
EXECUTE sp_executesql @SQL";