I am using one stored procedure in which I send @columnname
whose type in database is float
and I also declare parameter float
.
When I
You need dynamic sql.
DECLARE @SQL NVARCHAR(4000)
Declare @column varchar
set @column = 'S_E1'
SET @SQL = 'select Avg(' + quotename(@column) + ') from TBL_SENSORS'
EXEC sp_executesql @SQL
Update: applied both suggestions for quotename
and sp_executesql
New procedure: you can use dynamic SQL to place data into a temp table with a known schema. Refer to column based on alias: ColumnToAvg. Instead of TBL_SENSORS use #TempSensors.
Note: in production you'll want to check if #TempSensors exists and drop if it does.
SET @SQL = 'Select RECORD_TIMESTAMP, '
+ quotename(@ColumnName)
+ ' as ColumnToAvg
INTO #TempSensors
from TBL_SENSORS
Where RECORD_TIMESTAMP Between @StartDate and @EndDate
And @ColumnName Between @Start And @End'
EXECUTE sp_executesql @sqlCommand
, N'@StartDate datetime, @EndDate datetime, @Start int, @End int'
, @StartDate , @EndDate, @Start, @End