Skip to content
Advertisement

How do I select a table column which has the name of a variable in SQL?

DECLARE @TESTFN VARCHAR(8) = 'TEST'

IF OBJECT_ID('tempdb..#fnl_rec') IS NOT NULL DROP Table #fnl_rec

SELECT code INTO #fnl_rec FROM TEST_src WHERE 1=2

-- I tried this but it doesn't work

INSERT INTO #fnl_rec
   SELECT **@TESTFN** FROM TEST_Fnl

Advertisement

Answer

You can use Dynamic SQL to use variables for column names. Try this:

DECLARE @sql_stmt varchar(1000)
SET @sql_stmt = 'INSERT INTO #fnl_rec
                SELECT ' + @TESTFN + ' FROM TEST_Fnl'
EXEC @sql_stmt
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement