I am using SQL Server 2008 R2 and have run into an issue with my dynamic T-SQL query. I believe it has to do with my syntax however it runs in a new query window fine when taken out of the dynamic T-SQL context. When ran as a stored procedure I sometimes get the following error:
Column
dbo.Birds.weightis invalid in the select list because it is
not contained in either an aggregate function or theGROUP BY
clause.
T-SQL code:
set @sql =
N'select FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTinterval as ''Weight'',
COUNT(1) as ''Count''
FROM dbo.Birds
WHERE
weight >= @INPUTminwgt AND
weight <= @INPUTmaxwgt
GROUP BY FLOOR(weight*@INPUTconversion)
order by weight asc'
set @params =
N'@INPUTminwgt float,
@INPUTmaxwgt float,
@INPUTconversion float,
@INPUTinterval float';
exec sp_executesql @sql, @params,
@INPUTminwgt = @BirdMinWeight,
@INPUTmaxwgt = @BirdMaxWeight,
@INPUTconversion = @conversion,
@INPUTinterval = @interval;
The weights are go to the 1000 decimal place (e.g. 3.154)
@INPUTconversion = 1/interval
The query should return weights between the min and max weight parameters, grouped by the the interval (e.g. .1 intervals would be like 1.1, 1.2, 1.3, 1.4 with the counts of the total birds in that weight span)
Any help is appreciated
In the group by,
*@INPUTintervalsis missing.It should be
GROUP BY FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTintervalAlso,you can’t use the alias
weightin yourwhereandorder by, you have to useFLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTintervalordbo.Birds.weightcause here it’s ambiguous which one you need.