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

MYSQL
SQL语句因编写不当 可能导致系统不安全
教你如何缩小SQL Server数据库日志文件
sql2000卸载了后重新安装时不能安装的解决办法
MySQL密码忘记了,别害怕
如何防止插入删除表造成的数据库死锁
MySQL是否值得我们选择的正反五个理由
8种方法优化MySQL性能
MySQL服务器默认安装之后如何调节性能
MySQL数据库引擎快速指导
分析MS SQL Server里函数的两种用法
MYSQL数据库初学者使用指南
MySQL数据库安全配置指南
教你如何在MySQL数据库中直接储存图片
如何应用SQL Server DBCC避免堵塞
运用Mysql语句生成后门木马的具体方法
MySQL安全性指南 (1)
你的MySQL安全了吗?加铸23道安全门
MySQL中文参考手册---安装MySQL
MySQL管理员指南之--MySQL用户管理
如何利用MySQL加密函数保护Web网站敏感数据

MYSQL 中的 SQL实现动态交叉表


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-10-17   浏览: 71 ::
收藏到网摘: 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