我只想通过“Age_Band”分组进行简单查询。 并设置参数以帮助我轻松更改分组列。 但是得到了一个错误: “每个GROUP BY表达式必须包含至少一个不是外部引用的列。”
如何使用参数时出错?非常感谢
DECLARE @group nvarchar(50);
DECLARE @SQLString nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);
SET @SQLString =
N'SELECT AVG(Loan_Amount) as Avg_Loan_Amount
,count(Loan_Amount)
,SUM(Loan_Amount) as Sum_Loan_Amount
,SQRT(SUM(Loan_Amount)) as Square_Loan_Amount
,Age_Band
,SUM(Interest_Paid_Amount) as Sum_Interest_Paid_Amount
,GETDATE()as today
FROM [dbo].[Loan]
group by @groupcol';
SET @ParmDefinition = N'@groupcol nvarchar(50)';
SET @group=N'Age_Band'
exec sp_executesql @SQLString, @ParmDefinition,
@groupcol = @group;
答案 0 :(得分:0)
您不能在group by
子句中使用参数,您可以使用参数构建查询字符串。这样的事情。
DECLARE @group nvarchar(50) = N'Age_Band'; --set col name
DECLARE @SQLString nvarchar(500);
SET @SQLString =
N'SELECT AVG(Loan_Amount) as Avg_Loan_Amount
,count(Loan_Amount)
,SUM(Loan_Amount) as Sum_Loan_Amount
,SQRT(SUM(Loan_Amount)) as Square_Loan_Amount
,' + @group + '
,SUM(Interest_Paid_Amount) as Sum_Interest_Paid_Amount
,GETDATE()as today
FROM [dbo].[Loan]
group by ' + @group;
exec sp_executesql @SQLString;