简体   繁体   中英

How do I pass field name as a parameter into a stored procedure

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 pass column name as float then it gives the error:

Msg 8114, error converting data type nvarchar to float.

This is my test query

Declare @column float
set @column = 'S_E1'
select Avg(@column) from TBL_SENSORS

And when I change parameter type to varchar then it gives me this error:

Msg 8117, Operand data type varchar is invalid for avg operator.

Declare @column varchar
set @column = 'S_E1'
select Avg(@column) from TBL_SENSORS

How can I solve this?

UPDATE :

This is my stored procedure :

ALTER PROCEDURE [dbo].[getAvgColumn]
    @ColumnName float,
    @StartDate DateTime,
    @EndDate DateTime,
    @Start int,
    @End int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    declare @Skip int = 0
    declare @Take int = 4
    declare @count int = 0

    set @count = (select count(@ColumnName) from TBL_SENSORS Where RECORD_TIMESTAMP Between   @StartDate and @EndDate And ( @ColumnName Between @Start And @End ))

    while(@Skip < @count)
    Begin
        select avg(@ColumnName)
        from 
            (select 
                 @ColumnName as cc,
                 row_number() over (order by RECORD_TIMESTAMP) as rn
             from 
                 TBL_SENSORS 
             Where 
                 RECORD_TIMESTAMP Between @StartDate and @EndDate 
                 And (@ColumnName Between @Start And @End)
            ) T
    where 
        rn > @Skip and 
        rn <= @Skip + @Take

    set @Skip = @Skip + @Take
end
END

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM