Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Variables as Column Names

Posted on 2013-06-04
4
Medium Priority
?
341 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
4 Comments
 
LVL 9

Accepted Solution

by:
Beartlaoi earned 2000 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed

972 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