Guest User

Untitled

a guest
Jun 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.12 KB | None | 0 0
  1. `PIVOT (funcionDeAgregado(campoDeAgregado)FOR ColumnaPivote IN (valoresDeColumnaPivote)) AS Alias;`
  2.  
  3. USE [tuEsquema]
  4. GO
  5.  
  6. /****** Object: StoredProcedure [dbo].[prcPivotDinamic] Script Date: 6/21/2018 2:32:29 PM ******/
  7. SET ANSI_NULLS ON
  8. GO
  9.  
  10. SET QUOTED_IDENTIFIER ON
  11. GO
  12.  
  13. CREATE PROCEDURE [dbo].[prcPivotDinamic]
  14. -- Add the parameters for the stored procedure here
  15. @fchIni VARCHAR(255),
  16. @fchFin VARCHAR(255),
  17. @identificacion VARCHAR(255)
  18. AS
  19. BEGIN
  20.  
  21. SET NOCOUNT ON;
  22.  
  23. DECLARE @periodos AS NVARCHAR(MAX)
  24. DECLARE @PivotDynamicEsp NVARCHAR(MAX)
  25. DECLARE @PivotDynamicGnral NVARCHAR(MAX)
  26. DECLARE @dropViewGnral NVARCHAR(MAX)
  27. DECLARE @dropViewEsp NVARCHAR(MAX)
  28.  
  29. SELECT @periodos = COALESCE(@periodos + ', ', '')+ Quotename(Fecha)
  30. FROM
  31. (
  32. SELECT DISTINCT Fecha
  33. FROM consultHistoricoEstGnral
  34. WHERE Fecha BETWEEN @fchIni AND @fchFin
  35. GROUP BY Fecha
  36. ) AS periodos
  37.  
  38. --print 'periodos: '+@periodos;
  39.  
  40. SET @dropViewGnral = 'DROP VIEW MyPivotDynamicGnral'+@identificacion
  41.  
  42. --print @dropViewGnral
  43.  
  44. if object_id('MyPivotDynamicGnral'+@identificacion,'v') is not null
  45. EXEC sp_executesql @dropViewGnral
  46.  
  47. SET @dropViewEsp = 'DROP VIEW MyPivotDynamicEsp'+@identificacion
  48.  
  49. if object_id('MyPivotDynamicEsp'+@identificacion,'v') is not null
  50. EXEC sp_executesql @dropViewEsp
  51.  
  52. SET @PivotDynamicEsp = ' CREATE VIEW MyPivotDynamicEsp'+@identificacion+' AS
  53. SELECT
  54. EstadoEspecifico,
  55. '+@periodos+'
  56. FROM
  57. (
  58. SELECT
  59. CantidadEspecifica,
  60. EstadoEspecifico,
  61. Fecha
  62. FROM consultHistoricoEstEsp
  63. ) AS SourceTable
  64. PIVOT
  65. (
  66. SUM(CantidadEspecifica)
  67. FOR Fecha IN ('+@periodos+')
  68. ) AS PivotTable;
  69. '
  70. SET @PivotDynamicGnral = 'CREATE VIEW MyPivotDynamicGnral'+@identificacion+' AS
  71. SELECT
  72. EstadoGeneral,
  73. '+@periodos+'
  74. FROM
  75. (
  76. SELECT
  77. CantidadGeneral,
  78. EstadoGeneral,
  79. Fecha
  80. FROM consultHistoricoEstGnral
  81. ) AS SourceTable
  82. PIVOT
  83. (
  84. SUM(CantidadGeneral)
  85. FOR Fecha IN ('+@periodos+')
  86. ) AS PivotTable;'
  87.  
  88. --print @PivotDynamicGnral
  89.  
  90. IF(@periodos <> '')
  91. BEGIN
  92. EXEC sp_executesql @PivotDynamicEsp
  93. EXEC sp_executesql @PivotDynamicGnral
  94. print 'done'
  95. END
  96. ELSE
  97. PRINT 'notRow'
  98.  
  99.  
  100. END
  101. GO
Add Comment
Please, Sign In to add comment