1

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

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

这是我的测试查询

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

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

消息 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
4

1 回答 1

2

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

更新:应用了两个建议quotenamesp_executesql

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

注意:在生产中,您需要检查#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
于 2012-05-18T11:53:39.407 回答