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
Solved

Parameter in Select statement as column name

Posted on 2009-07-01
1
332 Views
Last Modified: 2012-05-07
I'm trying to select a specific column name from a table based on a string from a parameter.
How can I do this?
Code below...what I am trying to return is basically,

Select QA1 from @TEMP
if @QA = QA1.
DECLARE @VAL INT
	SET @VAL = 2
 
DECLARE @QA VARCHAR(5)
	SET @QA = 'QA'+CAST(@VAL AS VARCHAR(1))
 
DECLARE @TEMP TABLE
( PK INT, QA1 VARCHAR(4), QA2 VARCHAR(4) )
INSERT INTO @TEMP
	SELECT 1,'ASDF','JHFJ'
select * from @temp
 
SELECT @QA
FROM @TEMP

Open in new window

0
Comment
Question by:kcmoore
1 Comment
 
LVL 17

Accepted Solution

by:
pssandhu earned 50 total points
ID: 24757859
You have to use dynamic sql. Something like this for your select statment in the end
exec ('SELECT '+ @QA + ' FROM @TEMP')
P.

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

I am showing a way to read/import the excel data in table using SQL server 2005... Suppose there is an Excel file "Book1" at location "C:\temp" with column "First Name" and "Last Name". Now to import this Excel data into the table, we will use…
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.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

809 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