0

I was wondering if there is a way to select a column by using a SQL variable. Eg. Table is - ID, Name, Address

DECLARE @Column varchar(25)
SET @Column = 'Name' -- This can be another column also
SELECT @Column
FROM MyTable

This shows me 'Name' as many times as there are rows in my table. Is it even possible to do what I want ?

thanks.

Trojan.ZBOT
  • 1,218
  • 2
  • 14
  • 21
  • It is exactly that in my opinion, have you tried it? – NickyvV Nov 27 '13 at 22:53
  • While dynamic SQL will work, it can get very complicated very fast. It also fails to be reusable as it [cannot (easily) be combined with queries](http://stackoverflow.com/questions/1492411/sql-server-select-from-stored-procedure). (That is to say, I would advise against designs that are *based* around this operation.) – user2864740 Nov 27 '13 at 23:04

3 Answers3

3

Can do this with dynamic SQL:

DECLARE @Column varchar(25)
       ,@sql VARCHAR(MAX)
SET @Column = 'Name' -- This can be another column also
SET @sql = 'SELECT '+@Column+'
            FROM MyTable
            '
EXEC (@sql)

You can test your dynamic sql queries by changing EXEC to PRINT to make sure each of the resulting queries is what you'd expect.

Hart CO
  • 32,944
  • 5
  • 44
  • 59
2

You can use dynamic SQL for that:

DECLARE @Column nvarchar(25)
SET @Column = 'Name' -- This can be another column also
DECLARE @sql nvarchar(max) = N'SELECT ' + @Column + N' FROM MyTable'

exec(@sql)
Szymon
  • 41,995
  • 16
  • 94
  • 113
1

Sql is currently interpreting your variable as a string.

From a previous answer on stack overflow:

DECLARE @Column varchar(25)
SET @Column = 'Name' -- This can be another column also
SET @sqlText = N'SELECT ' + @Column + ' FROM MyTable'
EXEC (@sqlText)
Community
  • 1
  • 1
echochamber
  • 1,795
  • 1
  • 14
  • 17