列的类型" "与UNPIVOT列表中指定的其他列的类型冲突

时间:2017-04-25 05:57:41

标签: sql-server sql-server-2008

我已编写此查询以动态查找整个表中数值的最大值或最小值。我的查询是这样的:

declare @col varchar(2000)

 set @col = STUFF( (select ',' +' [' + c.name + ']'  FROM  
    sys.columns c
  INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
 WHERE
   c.object_id = OBJECT_ID('JRR_20170301_Stg')
   and c.system_type_id = 108 for XML path('')),1,1, '')

   select @col -- This returns the column name and good.

 --However, the problem starts from here below
  declare @sql varchar(max)

 set @sql='SELECT  max(col) 
 FROM JRR_20170301_Stg unPIVOT (col for ListofColumns in ('+@col+')) as unpivat'

   exec (@sql)

这是我的表结构:

    CREATE TABLE [dbo].[JRR_20170301_Stg](
[col1] [numeric](7, 0) NULL,
[col2] [numeric](7, 0) NULL,
[col3] [varchar](30) NULL,
[TIMESTAMP1] [varchar](8) NULL,
[BRANCH] [varchar](2) NULL,
[COE] [varchar](8) NULL,
[SCHEME] [varchar](3) NULL,
[NO] [varchar](7) NULL,
[PLAN] [varchar](5) NULL,
[ACODE] [varchar](8) NULL,
[ACTNAME] [varchar](30) NULL,
[SRNAME] [varchar](30) NULL,
[OTHERNAME] [varchar](30) NULL,
[ACTWTCH] [varchar](1) NULL,
[EMPLC] [varchar](5) NULL,
[EMPLNO] [varchar](13) NULL,
[LADATE] [numeric](7, 0) NULL,
[EARN] [numeric](7, 2) NULL,
[REGPA] [numeric](7, 2) NULL,
[OTAMT] [numeric](7, 2) NULL,
[EMPSTAT] [varchar](1) NULL,
[RESVE5] [varchar](100) NULL
) ON [PRIMARY]

有没有办法纠正这个错误并获得所需的结果?我可以使用交叉申请吗?

1 个答案:

答案 0 :(得分:1)

对于使用unpivat,所有字段都应为相同类型。您需要使用CASTCONVERT函数来制作它。

declare @col varchar(2000)
declare @colCAST varchar(4000)

 set @colCAST = STUFF( (select ',' +' CAST([' + c.name + '] AS numeric(7, 2)) AS [' + c.name + ']'  FROM  
    sys.columns c
  INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
 WHERE
   c.object_id = OBJECT_ID('JRR_20170301_Stg')
   and c.system_type_id = 108 for XML path('')),1,1, '')

 set @col = STUFF( (select ',' +' [' + c.name + ']'  FROM  
    sys.columns c
  INNER JOIN 
    sys.types t ON c.user_type_id = t.user_type_id
 WHERE
   c.object_id = OBJECT_ID('JRR_20170301_Stg')
   and c.system_type_id = 108 for XML path('')),1,1, '')

   select @col, @colCAST -- This returns the column name and good.

 --However, the problem starts from here below
  declare @sql varchar(max)

 set @sql='SELECT  max(col) 
 FROM 
 ( 
 SELECT ' + @colCAST + '
 FROM JRR_20170301_Stg
 ) s
  unPIVOT (col for ListofColumns in ('+@col+')) as unpivat'

   exec (@sql)