表sql server中具有最大整数值的列

时间:2017-04-24 10:30:53

标签: sql-server sql-server-2008-r2

此查询返回表中的最大整数值:

  SELECT rownum, max(col) as maxValue -- min 10717 , max = 311216
 FROM
  (
   SELECT rownum, col FROM Tables1
    UNPIVOT
   (col FOR ListofColumns IN 

  (col1,col2,col3,col4,col5, col6))
   AS unpivott) AS p
GROUP BY rownum

而不是" col1,col2,col3,col4,col5,col6"。我想使这个动态(自动从数据类型为int / numeric的表中获取)。

注意:有时候列数可能是50,我不想写每个列名。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

动态sql是唯一的方法。 你是这样开始的,

    create  table t1(rolname varchar(20),col1 int,col2 int,col3 int,col4 int)
insert into t1 values('a',32,45,23,645)
,('b',67,34,2673,344),('c',423,767,54,343),('d',676,43435,3432,4343)


declare @col varchar(2000)
select top 1
@col=stuff((select ','+'['+COLUMN_NAME+']' from INFORMATION_SCHEMA.COLUMNS b
where TABLE_NAME=a.TABLE_NAME and  DATA_TYPE='int'  for XML path('') ),1,1,'')
from INFORMATION_SCHEMA.COLUMNS a
where TABLE_NAME='t1'

select @col

declare @sql varchar(max)
set @sql='sELECT rolname, max(col)col
 FROM
  (
   SELECT * FROM t1
    UNPIVOT
   (col FOR ListofColumns IN 

  ( '+@col+'))
   AS unpivott) AS p
   GROUP BY rolname'

   exec (@sql)