문제

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  
도움이 되었습니까?

해결책

You need to use Dynamic SQL:

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

다른 팁

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top