set quoted_identifier on
goset ansi_nulls on
goalter 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+']'
endset @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
goset quoted_identifier off
goset ansi_nulls on
go
動態利用游標 實現行轉列
我的工作主要是報表,也沒有邏輯層,全部是靠sql 來實現功能,行轉列,列轉行.現在給大家分享一下,看看有沒有更好的方法啊!alter procedure corss strtabname varchar 50 表名 strcol varchar 50 列名 strgroup varchar 50 分...
動態交叉表的實現
declare sql varchar 8000 set sql select makedate,select sql sql sum case status when status then status else 0 end as status from select distinct stat...
動態交叉表的實現
create procedure corsstab strtabname as varchar 50 employees 此處放表名 strcol as varchar 50 city 表頭分組依據字段 strgroup as varchar 50 titleofcourtesy 分組字段 strn...