SELECT 动态列 GROUP BY 动态列
我需要在存储过程中完成以下操作:
- 传递参数化列名称。
- 选择参数化列名称并按所选列提供总组。
代码:
CREATE PROCEDURE sproc (
@column1 NVARCHAR(MAX),
@column2 NVARCHAR(MAX),
@startdate DATE,
@enddate DATE ) AS
BEGIN
DECLARE @sqlquery NVARCHAR(MAX) = 'SELECT @column1, @column2, SUM(amountcolumn)
FROM tablename
WHERE column3 = ''@value3'',
datecolumn BETWEEN ''@startdate'' AND ''@enddate''
GROUP BY @column1, @column2';
DECLARE @params NVARCHAR(MAX) = '@column1 VARCHAR(MAX),
@column2 VARCHAR(MAX),
@startdate DATE,
@enddate DATE';
EXEC sp_sqlexec @sqlquery, @params,
@column1 = @column1,
@column2 = @column2,
@startdate = @startdate,
@enddate = @enddate;
END
GO
I need to accomplish the following in the stored procedure:
- Pass parameterized column names.
- Select the parameterized column names and provide total group by selected columns.
Code:
CREATE PROCEDURE sproc (
@column1 NVARCHAR(MAX),
@column2 NVARCHAR(MAX),
@startdate DATE,
@enddate DATE ) AS
BEGIN
DECLARE @sqlquery NVARCHAR(MAX) = 'SELECT @column1, @column2, SUM(amountcolumn)
FROM tablename
WHERE column3 = ''@value3'',
datecolumn BETWEEN ''@startdate'' AND ''@enddate''
GROUP BY @column1, @column2';
DECLARE @params NVARCHAR(MAX) = '@column1 VARCHAR(MAX),
@column2 VARCHAR(MAX),
@startdate DATE,
@enddate DATE';
EXEC sp_sqlexec @sqlquery, @params,
@column1 = @column1,
@column2 = @column2,
@startdate = @startdate,
@enddate = @enddate;
END
GO
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设
@value3
是一个字符串,并且是存储过程的另一个参数,那么datecolumn
实际上是date
,并忽略我有的事实不知道如何拥有一个模式,其中分组字段可以像这样随机(您在此处忽略了其他最近的问题):这也假设您不关心顺序(您可能会并且想要添加
ORDER BY
以及如GROUP BY
)。有关动态 SQL 的更多信息,以及保护自己免受用户输入影响的进一步方法:
Assuming
@value3
is a string and is another parameter to the stored procedure, thatdatecolumn
is in factdate
, and ignoring the fact that I have no idea how you can have a schema where the grouping fields can be random like this (which you ignored in other recent questions here):This also assumes you don't care about order (you probably do and will want to add
ORDER BY
as well asGROUP BY
).For more info on dynamic SQL and even further ways to protect yourself from user input: