My requirement is to send Columnname as Parameter to Stored procedure and do SUM on that Column.
I have written a small stored procedure to accept the column name as a parameter and do sum on that but I am getting an error with it.
CREATE PROCEDURE dbo.testCol
-- Add the parameters for the stored procedure here
@type as nvarchar(20),
@beginDate as smalldatetime,
@endDate as smalldatetime
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
select dbo.mytable.date, sum(@type) as quantity
from dbo.mytable
where dbo.mytable.Date between @beginDate AND @endDate
group by dbo.mytable.date,dbo.mytable.day
order by dbo.mytable.date
END
GO
I am getting the error as "Operand data type nvarchar is invalid for sum operator." while executing this stored procedure.
Any help much appreciated.
Thanks
You’ll need to use dynamic sql to get the passed column name to be used this way in the query.
Use sp_executesql and include the column name in the string, and pass @beginDate and @endDate as parameters.