I am trying to create a procedure, that will accept as input a variable called @tablename
and will return as output the value of a variable called @myoutput
. As the names of the variables signify, @tablename
should be the name of a table and @myoutput
should be just be the sum of the the first column of the table specified by @tablename
, divided by the number 3.3. The procedure I have written is the following:
CREATE PROCEDURE sample_proc
@tablename VARCHAR(MAX),
@myoutput DECIMAL(20,5) OUTPUT
AS
SET NOCOUNT ON;
@myoutput=EXEC('SELECT SUM('+@tablename+'.column1)/3.3)'
When I just use EXEC()
, the select statement is executed as it should, but I cannot get the value I want from the table. What I want, is to store the value I calculate in the variable @myoutput
, and export that to my main script. The above code produces an error. Does anyone know how I can implement this?
Best Answer
First you're not using a valid syntax due your SELECT command has no FROM clause.
Then you should use sp_executesql just to take care of the output parameters.
dbfiddle here