简体   繁体   中英

SQL server: Invalid column name error

Here is my sql script, I want to set the aggregation method dynamically by using CASE:

select t.tagname,
  case t.aggregationmethod 
  when 'Sum' then SUM 
  when 'Average' then AVG 
  WHEN 'Max' then MAX 
  WHEN 'Min' THEN MIN ELSE SUM END +'('+tv.Value+')'
  from tag t, tagvalue tv where t.tagid=tv.tagid

when executed the script, it will pop up an error message:

    Invalid column name 'SUM'.
    Invalid column name 'AVG'.
    Invalid column name 'MAX'.
    Invalid column name 'MIN'.

My questions:
(1) how to fix my above script, where the problem is ?
(2) Is there other way to set aggregation method dynamically?

Your approach requires dynamic SQL. However, you can do this:

select t.tagname,
       (case t.aggregationmethod 
             when 'Sum' then SUM(tv.value)
             when 'Average' then AVG(tv.value)
             WHEN 'Max' then MAX(tv.value)
             WHEN 'Min' then MIN(tv.value)
             ELSE SUM(tv.value)
        end)
from tag t join
     tagvalue tv 
     on t.tagid = tv.tagid;

Note that I also changed the join syntax to be explicit rather than implicit.

Your problem is because the WHEN x THEN y syntax assumes that x is an expression and y is either a column or a constant value, or possibly an expression involving some columns. The way you have written the query does not satisfy these cases.

You can use dynamic SQL in order to construct the actual query dynamically based on your scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM