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

前端 未结 1 461
北荒
北荒 2021-01-24 23:50

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

相关标签:
1条回答
  • 2021-01-25 00:40

    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
    
    0 讨论(0)
提交回复
热议问题