小编典典

如何将字段名称作为参数传递给存储过程

sql

我正在使用一个存储过程,在其中发送@columnname数据库中其类型为的存储过程,float并且还声明parameter float
当我将列名传递为float时,它给出了错误:

消息8114,将数据类型nvarchar转换为float时出错。

这是我的测试查询

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

当我将参数类型更改为时,varchar它给了我这个错误:

消息8117,操作数数据类型varchar对avg运算符无效。

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

我该如何解决?

更新 :

这是我的存储过程:

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

阅读 260

收藏
2021-04-14

共1个答案

小编典典

您需要动态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

更新:同时应用了quotename和的建议sp_executesql

新过程:您可以使用动态SQL将数据放入具有已知模式的临时表中。请参考基于别名的列:ColumnToAvg。代替TBL_SENSORS使用#TempSensors。

注意:在生产中,您将要检查#TempSensors是否存在,如果存在则删除。

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
2021-04-14