行列转置的问题,谢谢!!1(200分)

  • 主题发起人 主题发起人 duxing
  • 开始时间 开始时间
D

duxing

Unregistered / Unconfirmed
GUEST, unregistred user!
现有表如下:
id size1 size2
123 34 43
124 21 44
125 65 77
126 34 84
现得到下面结果:
col1 col2 col3 col4
34 21 65 34
43 44 77 84
123 124 125 126
帮帮忙~谢谢!!!
 
写个存储过程就好了
 
to 1_1_1_1
能不能详细点!! 谢谢!
 
知道的兄弟~帮帮忙~~
 
if exists (select * from sysobjects where id = object_id('proc_ctor') and xtype ='P')
drop proc proc_ctor
go
create proc proc_ctor (@tablename varchar(200))
as
begin
set nocount on
declare @col nvarchar(256)
declare @makesql nvarchar(4000)
declare @insertsql nvarchar(4000)
declare @caculatesql nvarchar(400)
declare @count int
declare @i int
create table #tmp (colname nvarchar(20))
select @caculatesql = 'select @count=count(1) from ' + @tablename
exec sp_executesql @caculatesql, N'@count int output',@count output
if @count >=1024
begin
raiserror('行数太多',16,1)
end
else
begin
select @i=0
while @count >0
begin
select @i=@i+1
select @makesql = 'alter table #tmp add col'+convert(varchar(20),@i)+' int'
exec(@makesql)
select @count=@count-1
end
declare my_cursor cursor for
select name from syscolumns where id=object_id(@tablename) order by colid
open my_cursor
fetch next from my_cursor into @col
while @@fetch_status = 0
begin
select @makesql ='select @insertsql= @insertsql + convert(varchar(4),'+@col+') +'','' from ' +@tablename
select @insertsql =N'insert #tmp values ('''+@col+ ''','
execute sp_executesql @makesql,N'@insertsql nvarchar(4000) output' ,@insertsql output
select @insertsql = left(@insertsql,len(@insertsql)-1) +')'
exec(@insertsql)
fetch next from my_cursor into @col
end
close my_cursor
deallocate my_cursor
select * from #tmp
set nocount off
end
end

go
 
多人接受答案了。
 

Similar threads

I
回复
0
查看
418
import
I
I
回复
0
查看
843
import
I
I
回复
0
查看
490
import
I
I
回复
0
查看
680
import
I
后退
顶部