Question

I have a table with 20 columns. I am dynamically selecting a column according to the user input and then want to display the selected column with it's data. Here is the code I wrote but the issue is I am getting column name as the data for the selected column. Could anyone please let me know what I am doing wrong here.

ALTER PROCEDURE Getreport
@Subject [varchar](10),
WITH EXECUTE AS CALLER
AS
--Query to generate report

SELECT FirstName, LastName, @Subject FROM Student  
Was it helpful?

Solution

You need to use Dynamic SQL:

EXEC('SELECT FirstName, LastName,' + @Subject + ' FROM Student')

OTHER TIPS

Your procedure should look something like. Similar solution is shown here.

SET @s = CONCAT('SELECT FirstName, LastName, ', @Subject, ' FROM Student');
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top