--drop table #Tmp --删除临时表#TmpCREATE TABLE #Tmp --创建临时表#Tmp( AppliedIndustryNO int IDENTITY (1,1) not null, --创建列ID,并且每次新增一条记录就会加1 AppliedIndustryName varchar(50), primary key (AppliedIndustryNO) --定义AppliedIndustryNO为临时表#Tmp的主键 );Select * from #Tmp --查询临时表的数据truncate table #Tmp --清空临时表的所有数据和约束Declare @AppliedIndustryName Varchar(500) --用来记录名称Declare @Str NVarchar(4000) --用来存放查询语句Declare @Count int --求出总记录数 Declare @i intSet @i = 0 Select @Count = Count(Distinct(AppliedIndustryName)) from #TmpWhile @i < @Count Begin Set @Str = 'Select top 1 @AppliedIndustryName = AppliedIndustryName from #Tmp Where AppliedIndustryNO not in (Select top ' + Str(@i) + 'AppliedIndustryNO from #Tmp)' Exec Sp_ExecuteSql @Str,N'@AppliedIndustryName Varchar(500) OutPut',@AppliedIndustryName Output Select @AppliedIndustryName,@i --一行一行把名称显示出来 Set @i = @i + 1 End
来源:https://www.cnblogs.com/Warmsunshine/archive/2011/02/19/1958450.html