Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Aggregate function on a column supplied by a variable

Posted on 2011-03-01
3
Medium Priority
?
226 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
  • 2
3 Comments
 
LVL 8

Accepted Solution

by:
Forefront_Data_Solutions earned 2000 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

Get your Conversational Ransomware Defense e‑book

This e-book gives you an insight into the ransomware threat and reviews the fundamentals of top-notch ransomware preparedness and recovery. To help you protect yourself and your organization. The initial infection may be inevitable, so the best protection is to be fully prepared.

Question has a verified solution.

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

It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
This month, Experts Exchange sat down with resident SQL expert, Jim Horn, for an in-depth look into the makings of a successful career in SQL.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.

916 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