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
Assuming
@value3is a string and is another parameter to the stored procedure, thatdatecolumnis 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 BYas well asGROUP BY).For more info on dynamic SQL and even further ways to protect yourself from user input: