Solved

Variables as Column Names

Posted on 2013-06-04
4
325 Views
Last Modified: 2013-06-19
Can you declare a variable, set its value as a column name and pull based on the column?

IE:

DECLARE @WIDGET, varchar(255) = 'COLUMN1'

SELECT @WIDGET FROM MYTABLE

Open in new window


The select query should pull Column1 from mytable.  The idea is I want to build a script that would be easily reusable simply by changing the variables.
0
Comment
Question by:lm1189
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 9

Accepted Solution

by:
Beartlaoi earned 500 total points
ID: 39220248
No, that syntax would return the contents of @WIDGET

Dynamic SQL is how you do this kind of thing
DECLARE @WIDGET varchar(255)
SET @WIDGET = 'COLUMN1'
DECLARE @SQL varchar(MAX)
SET @SQL='SELECT ' + @WIDGET + ' FROM MYTABLE '
EXECUTE(@SQL)

Open in new window

0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 39220286
that could lead to SQL injection
0
 
LVL 23

Expert Comment

by:Racim BOUDJAKDJI
ID: 39220410
Not a good idea.  Poor caching, poor security, poor performance.
0
 
LVL 21

Expert Comment

by:Alpesh Patel
ID: 39228061
DECLARE @WIDGET, varchar(255) = 'COLUMN1'

SELECT @WIDGET

OR


SELECT @WIDGET, * FROM MYTABLE
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Removing SCCM 2016 4 53
SQL Query (lookup) 8 65
SQL Query 9 29
Group ordersum by orderdate 3 19
Why is this different from all of the other step by step guides?  Because I make a living as a DBA and not as a writer and I lived through this experience. Defining the name: When I talk to people they say different names on this subject stuff l…
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

738 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question