日期:2014-05-18 浏览次数:20691 次
create table tb(id int,a1 varchar(10),a2 varchar(10),a3 varchar(10),a4 varchar(10)) insert into tb values(1 ,'A', 'B', 'C', 'D') insert into tb values(2 ,'B', 'C', 'D', 'E') insert into tb values(3 ,'C', 'A', 'G', 'CD') insert into tb values(4 ,'A', 'B', 'S', 'AB') insert into tb values(5 ,'C', 'D', 'E', 'C') insert into tb values(6 ,'B', 'A', 'F', 'C') insert into tb values(7 ,'G', 'B', 'A', 'C') go declare @sql varchar(8000) select @sql=isnull(@sql + 'select left(reverse(','') + name + '),1) a from tb union ' from syscolumns where id=object_id('tb') and name != 'ID' select @sql='select max(a) 最大值 from (select left(reverse(' + left(@sql,len(@sql) - 5) + ') t' --print @sql exec(@sql) drop table tb /* 最大值 ---- S */
------解决方案--------------------
用游标吧,这是最笨的方法了
declare @Value varchar(10) declare @Sql varchar(100) declare @Max varchar(10) create table #tmp1(maxvalue varchar(10) null) declare cr_t1 cursor for select name from syscolumns where id=object_id('t1') and name <> 'ID' --从系统表中找到有多少个字段要计算 open cr_t1 FETCH NEXT FROM cr_t1 into @Value WHILE @@FETCH_STATUS = 0 BEGIN exec ('insert into #tmp1 select Max = max('+ @Value +') from tbdde1') FETCH NEXT FROM cr_t1 INTO @Value END CLOSE cr_t1 DEALLOCATE cr_t1 select max(maxvalue) from #tmp1