存储过程动态T-SQL查询无法正常工作

时间:2012-10-01 16:54:31

标签: sql tsql sql-server-2008-r2

我正在使用SQL Server 2008 R2并且遇到了动态T-SQL查询的问题。我相信它与我的语法有关,但是当从动态T-SQL上下文中取出时,它会在新的查询窗口中运行。当作为存储过程运行时,我有时会收到以下错误:

  

dbo.Birds.weight在选择列表中无效,因为它是   不包含在聚合函数或GROUP BY中   子句。

T-SQL代码:

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;

权重是小数点后1000位(例如3.154)

@INPUTconversion = 1/interval

查询应返回最小和最大权重参数之间的权重,按间隔分组(例如,.1间隔将类似于1.1,1.2,1.3,1.4,其中包含该权重范围内总鸟类的数量)

感谢任何帮助

2 个答案:

答案 0 :(得分:2)

在分组中,*@INPUTintervals缺失。

应为GROUP BY FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTinterval

此外,您无法在weightwhere中使用别名order by,您必须使用FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTintervaldbo.Birds.weight因为这里含糊不清你需要哪一个。

set @sql =
N'select FLOOR(dbo.Birds.weight * @INPUTconversion)*@INPUTinterval as ''Weight'',
COUNT(1) as ''Count''
FROM dbo.Birds
WHERE
dbo.Birds.weight >= @INPUTminwgt AND 
dbo.Birds.weight <= @INPUTmaxwgt
GROUP BY FLOOR(weight*@INPUTconversion) *@INPUTinterval
order by FLOOR(weight*@INPUTconversion) *@INPUTinterval asc'

答案 1 :(得分:0)

我的猜测是,它并没有完全认识到dbo.Birds.Weight与查询底部的“权重”相同。这当然很有趣,我不知道为什么这种情况正在发生,但这可能会有效:

set @sql = N'
SELECT 
  FLOOR(b.weight * @INPUTconversion) * @INPUTinterval as [Weight],
  COUNT(*) as ''Count''
FROM  dbo.Birds b
WHERE b.weight >= @INPUTminwgt 
AND   b.weight <= @INPUTmaxwgt
GROUP BY FLOOR(b.weight * @INPUTconversion) * @INPUTinterval
ORDER BY FLOOR(b.weight * @INPUTconversion) * @INPUTinterval'