ALTER PROCEDURE proc_hanglie
@tbname sysname, --要处理的表名或视图名
@fdname sysname, --作为转换后的列名
@new_fdname sysname='' --为转换前的列指定一个新列名
AS
/*
--行列互换通用存储过程: 将指定的表,按指定的字段进行行列互换
--Modified by windy8848
*/
declare @str1 nvarchar(max), @str2 nvarchar(max),
@str3 nvarchar(max), @str4 nvarchar(max),
@str5 nvarchar(max), @i varchar(10)
select @str1 = '' , @str2 = '' , @str3 = '' , @str4 = '' , @str5 = '' , @i = '0'
select @str1 = @str1 + ',@' + @i + ' nvarchar(max)',
@str2 = @str2 + ',@' + @i + '=''' + case isnull(@new_fdname , '') when '' then '' else @new_fdname + '=' end + '''''' + name + '''''''',
@str3 = @str3 + ' select @' + @i + '=@' + @i + '+'', ['' + [' + @fdname +']+'']=''+cast(isnull([' + name + '],0) as varchar) from [' + @tbname + ']',
@str4 = @str4 + ',@' + @i + '='' select ''+@' + @i,
@str5 = @str5 + '+'' union all ''+@' + @i,
@i=cast(@i as int)+1
from syscolumns
where object_name(id)=@tbname and name<>@fdname
select @str1=substring(@str1,2,8000),
@str2=substring(@str2,2,8000),
@str4=substring(@str4,2,8000),
@str5=substring(@str5,16,80000)
DECLARE @sql NVARCHAR(MAX)
SET @sql = 'declare ' + @str1 + ' select ' + @str2 + @str3 + ' select ' + @str4 + ' EXEC(' + @str5 + ')'
EXEC(@sql)
GO
|