Specifying Column Name As A Parameter in SELECT statement?

前端 未结 2 1346
后悔当初
后悔当初 2020-12-22 11:18

I need to do something like this, but it always fails with \'Error converting data type varchar to int\':

DECLARE @intParam INT
DECLARE @ColName VARCHAR(64)
         


        
相关标签:
2条回答
  • 2020-12-22 11:49

    You need to use dynamic sql:

    • build your dynamic SQL query (take a look at @SQL variable in sample below)
    • use output parameter to get value back from dynamic sql (take a look at @intParam and @intParam_out in sample below)
    • execute dynamic sql using sp_executesql
    DECLARE @intParam INT
    DECLARE @ColName VARCHAR(64)
    
    SET @ColName='intcolumn'
    
    DECLARE @SQL NVARCHAR(1000)
    SET @SQL = 'SELECT @intParam_out = ' + @ColName + ' FROM myTable'
    exec sp_executesql @SQL, N'@intParam_out int OUTPUT', @intParam_out = @intParam OUTPUT
    
    0 讨论(0)
  • 2020-12-22 11:56

    Use Cast:

    SET @intParam = SELECT cast(@ColName as int) FROM myTable
    
    0 讨论(0)
提交回复
热议问题