Solved

Variables as Column Names

Posted on 2013-06-04
4
320 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 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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

In this article I will describe the Copy Database Wizard method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Familiarize people with the process of retrieving data from SQL Server using an Access pass-thru query. Microsoft Access is a very powerful client/server development tool. One of the ways that you can retrieve data from a SQL Server is by using a pa…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties

773 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