Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 344
  • Last Modified:

Variables as Column Names

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
lm1189
Asked:
lm1189
1 Solution
 
BeartlaoiCommented:
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
 
Aneesh RetnakaranDatabase AdministratorCommented:
that could lead to SQL injection
0
 
Racim BOUDJAKDJIDatabase Architect - Dba - Data ScientistCommented:
Not a good idea.  Poor caching, poor security, poor performance.
0
 
Alpesh PatelAssistant ConsultantCommented:
DECLARE @WIDGET, varchar(255) = 'COLUMN1'

SELECT @WIDGET

OR


SELECT @WIDGET, * FROM MYTABLE
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now