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,398
  • 2
  • 14
  • 23
  • 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

4 Answers4

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
  • 34,064
  • 6
  • 48
  • 63
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
  • 42,577
  • 16
  • 96
  • 114
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,835
  • 1
  • 15
  • 18
0

I think you need to declare the sqltext as well

Max
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 16 '23 at 00:36