我需要在存储过程中完成以下操作:
代码:
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
答案 0 :(得分:2)
假设@ value3是一个字符串并且是存储过程的另一个参数,那个日期列实际上是DATE,而忽略了这样一个事实:我不知道你怎么能有一个模式,其中分组字段可以像这样随机(你在最近的其他问题中忽略了这一点):
DECLARE @sql NVARCHAR(MAX) = N'SELECT '
+ @column1 + ', ' + @column2 + ', SUM(amountcolumn)
FROM tablename
WHERE column3 = ''' + @value3 + '''
AND datecolumn BETWEEN ''' + CONVERT(CHAR(10), @startdate, 120) + '''
AND ''' + CONVERT(CHAR(8), @enddate, 120) + '''
GROUP BY ' + @column1 + ', ' + @column2 + ';';
EXEC sp_executesql @sql;
-- strongly recommend against sp_sqlexec
-- it is undocumented and unsupported
这也假设您不关心订单(您可能并且希望添加ORDER BY以及GROUP BY)。