当前位置: 首页 > 图文教程 > 数据库 > MYSQL > SQL实现动态交叉表

MYSQL
MySQL数据库中部分数据损坏恢复过程
教你怎样实现MySQL数据库双机热备份
MySQL数据库中关于网络安全的解决方案
最佳措施 全面解决MySQL网络安全问题
教你怎样在两台MySQL数据库间实现同步
忘记了 MySQL 的 root 密码
妙用触发器有效管理MySQL数据库
MYSQL5重置root密码
妙用触发器有效的管理 MySQL数据库
Mysql5写中文乱码问题解决
在MySQL中增添新用户权限的方法简介
教你维护MySQL安装的安全性和完整性
MySQL服务器安装完之后如何调节性能
MySQL出击企业级市场 “自立为王”尚早
MySQL 5.0 数据库的新特性的存储过程
通过MySQL内置全文检索实现中文的相关检索
MySQL中多表操作和批处理详细介绍
Oracle和MySQL、PostgreSQL特性对比
Sphinx+MySQL全文检索架构和安装过程
Mysql教程:教你为root用户指定一个目录

MYSQL 中的 SQL实现动态交叉表


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 40 ::
收藏到网摘: n/a

以下为引用的内容:
SET QUOTED_IDENTIFIER ON
  GO
  SET ANSI_NULLS ON
  GO
  ALTER procedure CrossTable
  @strTableName as varchar(50)='', --查询表
  @strCol as varchar(50)='',
  @strGroup as varchar(50)='',--分组字段
  @strNumber as varchar(50)='',--被统计的字段
  @strCompute as varchar(50)='Sum'--运算方式
  as
  declare @strSql as varchar(1000),@strTempCol as varchar(100)
  execute ('DECLARE corss_cursor CURSOR FOR SELECT DISTINCT '+@strCol+' from '+@strTableName+' for read only') --生成游标
  begin
  set nocount on
  set @strSql='select '+@strGroup+','+@strCompute+'('+@strNumber+') as ['+@strNumber+']'
  open corss_cursor
  while(0=0)
  begin
  fetch next from corss_cursor
  into @strTempCol
  if(@@fetch_status <>0) break
  set @strSql=@strSql+','+@strCompute+'( case '+@strCol+' when '''+@strTempCol+''' then '+@strNumber +' else 0 end ) as        ['+@strTempCol+']'
  end
  set @strsql=@strSql+' from '+@strTableName+' group by '+@strGroup
  print @strSql
  execute(@strSql)
  if @@error <>0 return @@error
  print @@error
  close corss_cursor
  deallocate corss_cursor return 0
  end
  GO
  SET QUOTED_IDENTIFIER OFF
  GO
  SET ANSI_NULLS ON
  GO