列转行时,无法确认所转列数时,处理语句

来源:互联网 发布:淘宝店铺制作教程 编辑:程序博客网 时间:2024/05/01 22:34
if not object_id('Class') is null    drop table ClassGoCreate table Class([Student] nvarchar(2),[数学] int,[物理] int,[英语] int,[语文] int)Insert Classselect N'李四',77,85,65,65 union allselect N'张三',87,90,82,78Go--2000:动态:declare @s nvarchar(4000)select @s=isnull(@s+' union all ','')+'select [Student],[Course]='+quotename(Name,'''')--isnull(@s+' union all ','') 去掉字符串@s中第一个union all+',[Score]='+quotename(Name)+' from Class'from syscolumns where ID=object_id('Class') and Name not in('Student')--排除不转换的列order by Colidexec('select * from ('+@s+')t order by [Student],[Course]')--增加一个排序


这里要注意一点的,这里使用了syscolumns系统表,所以大家在做测试的时候,不要使用临时表#temp这样的表,因为这个值

where ID=object_id('Class') 
是空的

原创粉丝点击