开发者

Error inserting into temporary table

开发者 https://www.devze.com 2023-02-15 08:26 出处:网络
I have a query but I get an error: Query: INSERT #tableN (ID,NAME,Value) SELECT 1 , \'subject\', SUM(subject), 2, \'age\', SUM(age),

I have a query but I get an error:

Query:

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 talePa开发者_StackOverflow社区rker

I get the following error:

Msg 203, Level 16, State 2, Line 61

The name 'INSERT #tableN (ID,NAME,Value) SELECT 1 , 'subject', SUM(subject),2 , 'age', SUM(age),3 , 'sex', SUM(sex),4 , 'test_time', SUM(test_time),' is not a valid identifier.


Your temporary table has three columns - yet your SELECT to insert has way more....

You need to break this up into several 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

Update: in SQL Server 2008, you could have:

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

but then you have to use fixed values - not SELECT expressions

Update #2: if you want to use a SUM(...) value, you'd have to get those first into variables:

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) .....


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
0

精彩评论

暂无评论...
验证码 换一张
取 消