Dynamic Pivot table wizard SQL Server

原文 http://www.gyurcit.hu/pivot.html

Dynamic Pivot table wizard

This stored procedure generate dynamic crosstable with multiple pivot columns by 4+1 parameters.

 

 

1. P_Row_Field Name of field that reperesent the spreadsheet's rows
2. P_Column_Field Name of field that store the name of columns
3. P_Value Name of field that represent the spreedsheet's value
4. P_From Name of source table
5. P_Where Filter expression (optional)

Values of second parameter field should not include apastrophe.  Procedure does not check paramaters (you must do that), so it may causes sql injection attack.

To source code click one of them

 

 
-- =================================================
-- Pivot Table Wizard            (c) 2009 by GyurcIT
-- http://www.gyurcit.hu   e-mail: gyurcit@gmail.com
-- =================================================

IF EXISTS (SELECT name FROM sysobjects
           WHERE  name = N'PivotWizard' AND type = 'P')
    DROP PROCEDURE PivotWizard
GO
-----------------------------------------------------
-----------------------------------------------------
CREATE PROCEDURE PivotWizard
   @P_Row_Field    VARCHAR(255),
   @P_Column_Field VARCHAR(255),
   @P_Value        VARCHAR(255),
   @P_From         VARCHAR(4000),
   @P_Where        VARCHAR(4000) = '1=1'
AS

  DECLARE @SQL NVARCHAR(4000)

  -- Build SQL statment that upload @Columns string 
  -- with @P_Column_Filed values
  CREATE TABLE #TEMP  (ColumnField varchar(100))
  SET @sql ='SELECT DISTINCT '+@P_Column_Field+' AS ColumnField'+
              ' FROM '+@P_From+
              ' WHERE '+@P_Where+
              ' ORDER BY '+@P_Column_Field
  INSERT INTO #TEMP
  EXEC(@sql)
  PRINT @sql

  -- Check count of columns
  DECLARE @Count_Columns int
  SELECT @Count_Columns = COUNT(*) FROM #Temp
  IF (@Count_Columns<1) OR (@Count_Columns>255)  BEGIN
      DROP TABLE #Temp
      RAISERROR('%d is invalid columns amount. Valid is 1-255',
16,1,@Count_columns)
      RETURN
  END
  -- Upload @Columns from #Temp
  DECLARE @Columns VARCHAR(8000),
          @Column_Field VARCHAR(8000)

  SET @Columns = ''
  DECLARE Column_cursor CURSOR LOCAL FOR
  SELECT CAST(ColumnField AS VARCHAR(60))
  FROM #Temp
  OPEN Column_cursor
  FETCH NEXT FROM Column_cursor
  INTO @Column_Field
  WHILE @@FETCH_STATUS = 0 BEGIN
      SET @Columns = @Columns +
        ' SUM('+
             ' CASE WHEN '+@P_Column_Field+'='''+ @Column_Field+''''+
             ' THEN '+@P_Value+
             ' ELSE 0 END'+
             ') AS ['+ @Column_Field +'], '
      FETCH NEXT FROM Column_cursor
      INTO @Column_Field
  END
  CLOSE Column_cursor
  DEALLOCATE Column_cursor
  DROP TABLE #Temp

  IF @Columns='' RETURN 1
  SET @Columns = Left(@Columns,Len(@Columns)-1)

  -- Build Pivot SQL statment
  DECLARE @Pivot_SQL VARCHAR(8000)
  SET @Pivot_SQL =              'SELECT '  +@P_Row_Field+', '+@Columns
  SET @Pivot_SQL = @Pivot_SQL +' FROM '    +@P_From
  SET @Pivot_SQL = @Pivot_SQL +' WHERE '   +@P_Where
  SET @Pivot_SQL = @Pivot_SQL +' GROUP BY '+@P_Row_Field
  SET @Pivot_SQL = @Pivot_SQL +' ORDER BY '+@P_Row_Field
  SET @Pivot_SQL = @Pivot_SQL + '#'

  IF Right(@Pivot_SQL,1)<>'#'
  BEGIN
     RAISERROR('SQL statement is too long. It must be less
                than 8000 charachter!',16,1)
     RETURN 1
  END
  SET @Pivot_SQL = Left(@Pivot_SQL,Len(@Pivot_SQL)-1)

  -- PRINT @Pivot_SQL
  EXEC(@Pivot_SQL)

  RETURN 0
GO

-- Example use Northwind database --
-- Example 1 --
exec PivotWizard 'ShipCountry',
                 'YEAR(OrderDate)*100+Month(OrderDate)',
                 '[ExtendedPrice]',
                 'dbo.Invoices',
                 'OrderDate BETWEEN ''1996/01/01'' and ''1996/12/31'''

GO

-- Example 2 --
exec PivotWizard 'ProductName',
                 'ShipCountry',
                 '[ExtendedPrice]',
                 'dbo.Invoices',
                 'OrderDate BETWEEN ''1996/01/01'' and ''1996/12/31'''
-- =================================================
-- Pivot Table Wizard MySQL      (c) 2009 by GyurcIT
-- http://www.gyurcit.hu   e-mail: gyurcit@gmail.com
-- =================================================
-- USE Database
DROP PROCEDURE IF EXISTS pivotwizard;

CREATE DEFINER = 'root'@'192.168.1.119'
PROCEDURE pivotwizard(
   IN P_Row_Field    VARCHAR(255),
   IN P_Column_Field VARCHAR(255),
   IN P_Value        VARCHAR(255),
   IN P_From         VARCHAR(4000),
   IN P_Where        VARCHAR(4000))
BEGIN
 DECLARE done INT DEFAULT 0;
 DECLARE M_Count_Columns int DEFAULT 0;
 DECLARE M_Column_Field varchar(60);
 DECLARE M_Columns VARCHAR(8000) DEFAULT '';
 DECLARE M_sqltext VARCHAR(8000);
 DECLARE M_stmt VARCHAR(8000);
 DECLARE cur1 CURSOR FOR SELECT CAST(Column_Field AS CHAR) FROM Temp;
 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

 DROP TABLE IF EXISTS Temp;
 SET @M_sqltext = CONCAT('CREATE TEMPORARY TABLE Temp ',
                   ' SELECT DISTINCT ',P_Column_Field, 
				' AS Column_Field',
                   ' FROM ',P_From,
                   ' WHERE ',P_Where,
                   ' ORDER BY ', P_Column_Field);

 PREPARE M_stmt FROM @M_sqltext;
 EXECUTE M_stmt;

 SELECT COUNT(*) INTO M_Count_Columns 
 FROM Temp 
 WHERE Column_Field IS NOT NULL;

 IF (M_Count_Columns > 0) THEN
    OPEN cur1;
    REPEAT
      FETCH cur1 INTO M_Column_Field;
      IF (NOT done) and (M_Column_Field IS NOT NULL) THEN
         SET M_Columns = CONCAT(M_Columns,
' SUM( CASE WHEN ',P_Column_Field,'=''',M_Column_Field,'''',
         		' THEN ',P_Value,
                  ' ELSE 0 END) AS `', M_Column_Field ,'`,');

      END IF;
    UNTIL done END REPEAT;
    SET M_Columns = Left(M_Columns,Length(M_Columns)-1);
    SET @M_sqltext = CONCAT('SELECT ',P_Row_Field,',',M_Columns,
                            ' FROM ', P_From,
                            ' WHERE ', P_Where,
                            ' GROUP BY ', P_Row_Field,
                            ' ORDER BY ', P_Row_Field);

    PREPARE M_stmt FROM @M_sqltext;
    EXECUTE M_stmt;
  END IF;
END
-- Example:
CALL pivotwizard('article','Month(date)',
'netto',
'invoice',
'(year(date)=2009)')

 

 
时间: 2024-12-27 02:22:24

Dynamic Pivot table wizard SQL Server的相关文章

SQL Server里PIVOT运算符的”红颜祸水“

原文:SQL Server里PIVOT运算符的"红颜祸水" 在今天的文章里我想讨论下SQL Server里一个特别的T-SQL语言结构--自SQL Server 2005引入的PIVOT运算符.我经常引用这个与语言结构是SQL Server里最危险的一个--很快你就会知道为什么.在我们进入特定问题和陷阱前,首先我想给你下使用SQL Server里的PIVOT能实现什么的一个基本概述. 概述 SQL Server里PIVOT运算符背后的基本思想是在T-SQL查询期间,你可以旋转行为列.运

SQL Server -&gt;&gt; 深入探讨SQL Server 2016新特性之 --- Temporal Table(历史表)

原文:SQL Server ->> 深入探讨SQL Server 2016新特性之 --- Temporal Table(历史表) 作为SQL Server 2016(CTP3.x)的另一个新特性,Temporal Table(历史表)记录了表历史上任何时间点所有的数据改动.Temporal Table其实早在ANSI SQL 2011就提出了,而SAP HANA, DB2和Oracle早已在它们的产品中加入/实现了这一特性.所以说微软其实是落后了几个竞争对手.既然在CTP3.0中加入了,相信

SQL Server 2008性能故障排查(一)——概论

原文:SQL Server 2008性能故障排查(一)--概论 备注:本人花了大量下班时间翻译,绝无抄袭,允许转载,但请注明出处.由于篇幅长,无法一篇博文全部说完,同时也没那么快全部翻译完,所以按章节发布.由于本人水平有限,翻译结果肯定存在问题,为了不造成误导,在每篇结尾处都附上原文,供大家参考,也希望能指出我的问题,以便改进.谢谢. 另外,本文写给稍微有经验的数据库开发人员或者DBA看,初学者可能会看不懂.在此请见谅 作者:Sunil Agarwal, Boris Baryshnikov, K

Display Database Image using MS SQL Server 2008 Reporting Services

原文 Display Database Image using MS SQL Server 2008 Reporting Services With the new release of MS SQL Server 2008 Reporting Services has introduced a new feature that will help report developers (Business Intelligence BI professionals) to display imag

SQL Server 2000 的工具

1.3.4 ProfilerSQL Server Profiler 是一个图形化的管理工具用于监督记录和检查SQL Server 数据库的使用情况对系统管理员来说它是一个监视用户活动的间谍 1.3.5 Client Network Utility SQL Server Client Network Utility 用于配置客户端的连接测定网络库的版本信息以及设定本地数据库的相关选项 1.3.6 Server Network UtilitySQL Server Server Network Uti

Access与Sql Server之ASP代码比较

access|server|sql|比较 后台数据库: [Microsoft Access] 与 [Microsoft Sql Server] 更换之后,ASP代码应注意要修改的一些地方: [一]连接问题(举例) [Microsoft Access] constr = "DBQ=c:\data\clwz.mdb; DRIVER={Microsoft Access Driver (*.mdb)}" [Microsoft Sql Server] constr = "DRIVER=

技巧:Access与Sql Server之ASP代码比较

access|server|sql|比较|技巧 后台数据库: [Microsoft Access] 与 [Microsoft Sql Server] 更换之后,ASP代码应注意要修改的一些地方: [一]连接问题(举例) [Microsoft Access] constr = "DBQ=c:\data\clwz.mdb; DRIVER={Microsoft Access Driver (*.mdb)}" [Microsoft Sql Server] constr = "DRIV

MS SQL基础教程:SQL Server 2000的工具

1.3.4 Profiler SQL Server Profiler 是一个图形化的管理工具用于监督记录和检查SQL Server 数据库的使用情况对系统管理员来说它是一个监视用户活动的间谍 1.3.5 Client Network Utility SQL Server Client Network Utility 用于配置客户端的连接测定网络库的版本信息以及设定本地数据库的相关选项 1.3.6 Server Network Utility SQL Server Server Network U

SQL Server的Collate语句需注意

汗,今天被Sql Server的Collate子句大玩了一把,看在线帮助不仔细!让自己绕了一个大圈,以后看MS帮助可要仔细了,事情是这样的: 下午,老大给我们发来一段SQL Script,要我们测试,看有没有错误,如有,请提出!整个Script全部在这里! 我当时就将这段脚本拉进了查询分析器,一执行,呵呵,根本没错啊!那老大为什么要发这样的邮件出来呢?于是我又切换了几个database,也没有什么问题,正当我准备测试完这一个database就放弃测试退出的时候,问题来了.错误消息如下: Serv