Solved

Aggregate function on a column supplied by a variable

Posted on 2011-03-01
3
207 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 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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

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…
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
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.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.

786 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