Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Variables as Column Names

Posted on 2013-06-04
4
Medium Priority
?
333 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 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

Prepare for your VMware VCP6-DCV exam.

Josh Coen and Jason Langer have prepared the latest edition of VCP study guide. Both authors have been working in the IT field for more than a decade, and both hold VMware certifications. This 163-page guide covers all 10 of the exam blueprint sections.

Question has a verified solution.

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

A Stored Procedure in Microsoft SQL Server is a powerful feature that it can be used to execute the Data Manipulation Language (DML) or Data Definition Language (DDL). Depending on business requirements, a single Stored Procedure can return differe…
Ready to get certified? Check out some courses that help you prepare for third-party exams.
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 and will be exposed to the many uses the SELECT statement has.

670 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