Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SPROC GROUP BY variables

Status
Not open for further replies.

icarus5000

Technical User
May 15, 2003
16
US
Hi,

I'm trying to create a sproc that is using parameters for dynamic field names. The following sql statement is causing problems with using the sproc parameters in the GROUP BY clause. Is there a way around this apart from writing an IF statement for each field iteration.

SELECT @group1,@group2,CRS_ID,COUNT(STATUS) as status_total
FROM TBLMAIN
WHERE STATUS='C' AND COMP_ID=@CompID
GROUP BY @group1, @group2, CRS_ID

Thanks,
Ic
 
Whoops! Sorry.

Here's the error from query analyser

Server: Msg 164, Level 15, State 1, Procedure sp_assigned_summary, Line 30
GROUP BY expressions must refer to column names that appear in the select list.

Thanks,
Ic
 
you will need to use dynamic sql if you want to do it this way.

Code:
DECLARE @group1 as varchar(300)
DECLARE @group2 as varchar(300)
DECLARE @CompID as varchar(300)
select @CompID = 'c1'
select @group1 = 'g1'
select @group2 = 'g2'

DECLARE @sql as varchar(8000)

select @sql = 'SELECT ' + @group1 + ',' + @group2 + ',CRS_ID,COUNT(STATUS) as status_total
FROM TBLMAIN
WHERE STATUS=''C'' AND COMP_ID=' + @CompID +
' GROUP BY ' + @group1 + ', ' + @group2 + ', CRS_ID'

print @sql
exec (@sql)
 
Code:
SELECT @group1, @group2, CRS_ID, status_total
FROM
(	SELECT CRS_ID, COUNT(STATUS) as status_total
	FROM TBLMAIN
	WHERE STATUS='C' AND COMP_ID=@CompID
	GROUP BY CRS_ID
) blah

------
"There's a man... He's bald and wears a short-sleeved shirt, and somehow he's very important to me. I think his name is Homer."
(Jack O'Neill, Stargate)
[banghead]
 
Damn... I'm dunkin' too much.

Simply name columns:

Code:
SELECT @group1 as blah,@group2 as blah2 ,CRS_ID,COUNT(STATUS) as status_total
FROM TBLMAIN
WHERE STATUS='C' AND COMP_ID=@CompID
GROUP BY blah1, blah2, CRS_ID

------
"There's a man... He's bald and wears a short-sleeved shirt, and somehow he's very important to me. I think his name is Homer."
(Jack O'Neill, Stargate)
[banghead]
 
This worked out very nicely.

Thanks a million!
-Ic

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top