Solved

Aggregate function on a column supplied by a variable

Posted on 2011-03-01
3
219 Views
Last Modified: 2012-05-11
Here is the dilemma.  I have a stored procedure where I need to grab the AVG of a column containing chemistry data.   There is a separate column for all chemistries we track, roughly 26 of them.  C, ZR, Pb, etc. etc.   This stored procedure needs to just do the avg on the chemistry that the user selects.

Is there a way to do this dynamically by passing the column name as a variable?

Below is a version that I attempted, but I get the error:

The name 'SELECT TOP 1 Avg[C] FROM XXXX GROUP BY Type' is not a valid identifier.
DECLARE @SQL2 varchar(1000)

BEGIN

DECLARE @in nvarchar(5)
SET @in = 'C'

SET @SQL2 = 'SELECT TOP 1 Avg['+@in+'] FROM XXXX GROUP BY Type'
EXEC @SQL2
END

Open in new window

0
Comment
Question by:hscast
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 8

Accepted Solution

by:
Forefront_Data_Solutions earned 500 total points
ID: 35007461
Use parentheses instead:  

SET @SQL2 = 'SELECT Avg('+@in+') FROM XXXX GROUP BY Type'

I also don't think you need "Top 1"
0
 

Author Comment

by:hscast
ID: 35007493
Nevermind.  Added ( after Avg and ) after the end bracket and it worked.
0
 

Author Comment

by:hscast
ID: 35007496
Whoops.  Quick answer Forefront!  I'll give you the points still.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question