I have a 'conceptual' question. I understand how to create a simple stored procedure with parameters.
My question now is, how do I write a stored procedure such that the columns I want to SELECT ... FROM are dynamic.
Example run 1: I want to run a stored procedure by only
SELECT firstName, LastName
Example run 2: I want to run a stored procedure by only
SELECT firstName, LastName, Department
The columns I want to SELECT list each time I run the stored procedure can change.
I have an existing stored procedure (_SelectFromQry) written like this:
ALTER PROCEDURE [dbo].[_SelectFromQry]
@queryname NVARCHAR(255)
AS
BEGIN
SELECT TBLNAME, TBLCOL, TBLCOLLABEL, POSITION
FROM QRY
WHERE QUERYNAME = @queryname
END
The result of the above procedure is the 'dynamic columns' that I want to SELECT from another table.
I have no clear idea how to write a stored procedure which SELECT FROM another table according to the results of '_SelectFromQry'. Would it involve creating some sort of 'list parameter' where I would SELECT FROM @LIST ?
Appreciate any kind of help.
IF-ELSEor throughDynamic SQL