插入临时表时出错

时间:2011-03-04 16:47:14

标签: sql-server-2008

我有查询,但收到错误:

查询:

INSERT #tableN (ID,NAME,Value) 
  SELECT 1 , 'subject', SUM(subject), 2, 'age', SUM(age), 
         3, 'sex', SUM(sex), 4, 'test_time', SUM(test_time) 
  FROM taleParker

我收到以下错误:

  

Msg 203,Level 16,State 2,Line 61
  名称'INSERT #tableN   (ID,NAME,Value)SELECT 1,'subject',   SUM(主题),2,'年龄',SUM(年龄),3,   'sex',SUM(性别),4,'test_time',   SUM(test_time),'不是有效的   标识符

2 个答案:

答案 0 :(得分:2)

您的临时表有三列 - 但您要插入的SELECT还有更多....

您需要将其分解为多个INSERTs

INSERT #tableN (ID,NAME,Value) 
  SELECT 1 , 'subject', SUM(subject)
  FROM taleParker

INSERT #tableN (ID,NAME,Value) 
  SELECT 2, 'age', SUM(age)
  FROM taleParker

INSERT #tableN (ID,NAME,Value) 
  SELECT 3, 'sex', SUM(sex)
  FROM taleParker

INSERT #tableN (ID,NAME,Value) 
  SELECT 4, 'test_time', SUM(test_time) 
  FROM taleParker
SQL Server 2008中的

更新:,您可以:

INSERT #tableN (ID,NAME,Value) 
   VALUES(1, 'subject', 1), (2, 'age', 42), (3, 'sex', 'M') .....

但是你必须使用固定值 - 而不是SELECT表达式

更新#2:如果您想使用SUM(...)值,则必须先将这些值转换为变量:

DECLARE @SumSubj INT, @SumAge INT, @SumSex INT, @SumTest INT

SELECT @SumSubj = SUM(subject), @SumAge = SUM(age),
       @SumSex = SUM(sex), @SumTest = SUM(test_time)
FROM taleParker

INSERT #tableN (ID,NAME,Value) 
   VALUES(1, 'subject', @SumSubj), (2, 'age', @SumAge), (3, 'sex', @SumSex) .....

答案 1 :(得分:2)

INSERT #tableN (ID,NAME,Value) 
  SELECT 1, 'subject', SUM(subject) FROM taleParker  UNION ALL
  SELECT 2, 'age', SUM(age) FROM taleParker  UNION ALL
  SELECT 3, 'sex', SUM(sex) FROM taleParker UNION ALL 
  SELECT 4, 'test_time', SUM(test_time) FROM taleParker