Thanks for the reply Joe. I tried the code and put it in a stored procedure and it worked. However, I cannot combine it with WHERE clause. I tried using parametarized stored proc and it returns an error. The stored proc goes like this:
ALTER PROCEDURE dbo.myStoredProc
(
@prmproject_id nvarchar(50),
@prmfieldname nvarchar(50),
@prmaverage nvarchar(50)
)
AS
DECLARE @mySQL nvarchar(1000)
DECLARE @columnname sysname
SET @columnname=@prmfieldname
SET @mySQL = 'SELECT ' + @columnname + ' FROM CompletionRateAverage '
EXECUTE(@mySQL)
This works fine.
But when I tried combining WHERE clause as in:
SET @mySQL = 'SELECT ' + @columnname + ' FROM CompletionRateAverage ' + 'WHERE project_id = @prmproject_id'
Must declare the variable '@project_id' error is returned.
When I tried to change the statement to:
SET @mySQL = 'SELECT ' + @columnname + ' FROM CompletionRateAverage ' + 'WHERE project_id ='+ @prmproject_id
Invalid Column Name <value of project_id> is returned. As if the value of the project_id field is treated as column name.
Please help... Thanks!
|