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

时间:2012-05-18 11:45:00

标签: sql sql-server

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

  

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

这是我的测试查询

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

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

  

Msg 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

1 个答案:

答案 0 :(得分: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

更新:对quotenamesp_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